我正在开发一个程序,将用户输入写入文件,然后在文件中搜索特定记录并将其输出到屏幕。
我尝试使用 fgets 和 fputs,但都没有成功。这是我目前所拥有的。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
main ()
{
FILE *fileptr;
char id [30];
char name [47];
char amt[50];
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;
}
最佳答案
使用:
fscanf(stdin, "%s", name);
但更好的是,如 kol 所述,改用 scanf。这是因为 scanf() 旨在从屏幕读取用户响应,而 fscanf() 用于扫描任何输入流(通常是文件)。
并且该语句应该从屏幕 (stdin) 中读取,而不是从文件中读取(该文件仅以“写入”方式打开)。
关于c - 在 C 编程中将用户输入写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8115944/