首页 > 解决方案 > 如何在 C 中编辑文件?

问题描述

我是 C 的新手,正在尝试为酒店编写一个程序,让客户编辑他们的预订详细信息,例如名字、姓氏……等。我写的代码可以运行,但是文件中的数据没有被编辑。

("Record not found! Please enter your Username and Password again.\n");当我输入错误的用户名和密码时,也不会打印该行的 else 语句。

这是我到目前为止得到的:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h> 
#include <string.h>  
#include <stdbool.h>

struct customer_details  // Structure declaration
{
    char uname[100];
    char pass[100];
    char fname[100];
    char lname[100];
    char ic[100];
    char contact[100];
    char email[100];
    char room[100];
    char day[100];
 }s;


void main()
{
    FILE* f, *f1;
    f = fopen("update.txt", "r");
    f1 = fopen("temp.txt", "w");
    char uname[100], pass[100];
    int valid = 0;

   // validate whether file can be opened.
   if (f == NULL)
   {
       printf("Error opening file!\n");
       exit(0);
   }

   printf("Please enter your Username and Password to update your booking detail.\n");
   printf("\nUsername: ");
   fgets(uname, 100, stdin);
   uname[strcspn(uname, "\n")] = 0;
   printf("Password: ");
   fgets(pass, 100, stdin);
   pass[strcspn(pass, "\n")] = 0;
   while (fscanf(f, "%s %s", s.uname, s.pass) != -1)
   {
       if (strcmp(uname, s.uname) == 0 && strcmp(pass, s.pass) == 0)
       {
           valid = 1;
           fflush(stdin);
           printf("Record found!\n");
           printf("\nEnter First Name: ");
           scanf("%s", &s.fname);
           printf("\nEnter Last Name: ");
           scanf("%s", &s.lname);
           printf("\nEnter IC Number: ");
           scanf("%s", &s.ic);
           printf("\nEnter Contact Number:");
           scanf("%s", &s.contact);
           printf("\nEnter Email: ");
           scanf("%s", &s.email);
           printf("\nEnter Room ID :");
           scanf("%s", &s.room);
           printf("\nEnter Days of staying:");
           scanf("%s", &s.day);
           fseek(f, sizeof(s), SEEK_CUR); //to go to desired position infile
           fwrite(&s, sizeof(s), 1, f1);
        }
       else
           ("Record not found! Please enter your Username and Password again.\n");
   }
   fclose(f);
   fclose(f1);
   if (valid == 1)
   {
    
       f = fopen("update.txt", "r");
       f1 = fopen("temp.txt", "w");
       while (fread(&s, sizeof(s), 1, f1))
       {
           fwrite(&s, sizeof(s), 1, f);
       }
       fclose(f);
       fclose(f1);
       printf("Record successfully updated!\n");
   }
}

这是 update.txt 文件包含的内容:

abc 123 前 后 234 33667 hi@gmail.com 101 3

标签: c

解决方案


你忘记了printf调用,改变

("Record not found! Please enter your Username and Password again.\n");

printf("Record not found! Please enter your Username and Password again.\n");

如果您在启用警告的情况下编译程序,您应该会收到类似的警告

t.c:68:12: warning: statement with no effect [-Wunused-value]
            ("Record not found! Please enter your Username and Password again.\n");
            ^

推荐阅读