我正在开发一个程序,将用户输入写入文件,然后搜索文件中的特定记录并将其输出到屏幕。
我尝试使用 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;
}
Use:
fscanf(stdin, "%s", name);
但更好的是,使用 scanf 代替,正如 kol 提到的那样。这是因为 scanf() 旨在从屏幕读取用户响应,而 fscanf() 用于从任何输入流(通常是文件)进行扫描。
并且该语句应该从屏幕(stdin)读取,而不是从文件(仅以“写入”方式打开)读取。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)