我正在尝试制作一个程序,它将用户输入的数据存储在一个文本文件中,该文件的名称由用户提供。当用户输入 exit 时,程序将终止。 string.h的strcmp函数用于字符串比较,fgets()用于从stdin读取数据。
这是我的代码。
#include<stdio.h>
#include<string.h>
void main()
{
char file[60]; // will store file name
printf("Enter file name: ");
fgets(file, 59, stdin);
FILE *fp = fopen(file, "a+"); // open file in append mode
if(fp == NULL){
printf("File not found !");
return;
}
char data[100];
printf("Enter some data to add to file(exit to terminate): ");
fgets(data, 99, stdin);
int flag = strcmp(data, "exit");
while(flag != 0){
fputs(data, fp);
fgets(data, 59, stdin);
flag = strcmp(data, "exit");
printf("%d\n", flag); // for checking whether string are correctly comapred or not
}
printf("Bye");
}
即使我输入 exit,程序也不会终止。我还尝试在用户输入的字符串末尾连接“\n”,但这也无济于事。虽然 gets() 函数工作正常,但我知道它不是我转向 fgets() 的首选,但它对我不起作用。
最佳答案
检查 man page对于 fgets()
,它读取并存储输入后的换行符(由按 ENTER 引起)。因此,strcmp()
失败。
在比较输入之前,您必须手动从换行符中删除输入缓冲区。一种简单而优雅的方法是
data[strcspn(data, "\n")] = 0;
关于c - C 中的 fgets 函数和文件处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53209676/