将用户输入写入C中的文件

我正在开发一个程序,用于将用户输入写入文件,然后在文件中搜索特定记录并将其输出到屏幕。 我尝试过使用fgets和fput但是还没有成功

#include  #include  #include  main () { FILE *fileptr; char id [30]; char name [47]; char amt[50]; int i; fileptr=fopen("C:\\Users\\Andrea\\Documents\\Tester.txt","w"); if (fileptr == NULL) { printf("File couldn't be opened\n\a\a"); fclose(fileptr); exit(0); } printf("Enter name: \n"); fscanf(fileptr,"%c",name); fputs(name,fileptr); fclose(fileptr); printf("File write was successful\n"); return 0; } 

有几个问题。

  1. 您正在尝试从fileptr读取。
  2. 您只读取一个字符,但将name数组视为正确读取它。

一个开始是:

  [...] printf("Enter name: \n"); if (fgets(name, sizeof name, stdin)) { fputs(name,fileptr); fclose(fileptr); printf("File write was successful\n"); } else { printf("Read error.\n"); } 

但这不是全部:你忘记了错误检查。 例如,如果你不至少检查fputs()的返回值,你怎么知道你的"File write was successful\n"