c - 如何在 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
解决方案
你忘记了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");
^
推荐阅读
- json - 如何在 spark 2.3.0 结构化流中轻松地从 kafka 中提取已知类的 json 数据
- java - 在 MacOS 上安装 Hadoop 导致 CMake 构建失败
- android - Android Studio 约束布局以编程方式向右对齐
- c# - 如何在 C# 中使用文本框和按钮单击过滤 datagridview?
- c# - 如何使用firesharp从firebase作为对象返回
- angular - ionic - Google 地图标记未显示
- python - 从嵌套列表制作数据框
- php - PHP preg_replace 与 \s 在 Windows 中工作不同
- android - 这个 NPE 的原因是什么?
- ios - 如何从 Swift 4/json 字典中的多值键中检索单个值?