[英]Problems reading C txt file
我正在制作一个C程序,当用户关闭该程序时,我需要它来保存一些整数和字符串。 我成功地做到了。 txt文件已创建并且所有内容均已正确编写,问题是,当我尝试在编译器上读取它时,它无法正常工作。 我的代码是:编写:
saveFile = fopen("saveFileP.txt", "w");
for (int i=0; i<numberofPeople; i++) {
fputs(people[i].firstName, saveFile);
fputs(" ", saveFile);
fputs(people[i].lastName, saveFile);
fputs(" ", saveFile);
fprintf(saveFile, "%d ", people[i].cash);
fprintf(saveFile, "%d ", people[i].position);
fprintf(saveFile, "%d ", people[i].inGame);
}
读书:
saveFile = fopen("saveGameP.txt", "r");
for (int i=0; i<numberOfPeople; i++) {
fgets(people[i].firstName, 20, saveFile);
fgets(people[i].lastName, 20, saveFile);
fscanf(saveFile, "%d", &people[i].cash);
fscanf(saveFile, "%d", &people[i].position);
fscanf(saveFile, "%d", &people[i].inGame);
}
然后我要求它将值打印到屏幕上,并写入错误的值,但是在txt文件中,这些值是正确的。 我究竟做错了什么? 谢谢。
PS:我正在使用Xcode。
尝试
for (int i=0; i<numberOfPeople; i++) {
fscanf(saveFile,"%s %s",people[i].firstName,people[i].lastName);
fscanf(saveFile, "%d", &people[i].cash);
fscanf(saveFile, "%d", &people[i].position);
fscanf(saveFile, "%d", &people[i].inGame);
}
我使用fscanf()
是因为fgets()
读取整行,直到遇到\\n
字符(或直到读取最多20个字符)为止,直到找到空格为止。 由于firstName
和lastName
都用空格分隔,因此可以使用fscanf()
。
fgets()
读取直到换行符为止,并且包括\\n
在这种情况下,姓氏和姓氏是否不在同一行中,并用空格分隔?
在您的代码中,您正在读取第一行,并且仅读取前20个字符,其余未读取。
然后,您将移至下一行而不实际阅读下一部分。
您可以通过执行此操作来解决此问题
fgets()
阅读整行 strtok()
并使用空格作为定界符将行换成令牌 我建议使用getline(尽管未在POSIX中指定),使用它来读取整行(以验证使用printf来打印该行)
然后,例如,如果您的值用空格分隔。 使用strtok函数标记刚刚阅读的行。
例如:
strtok("123: A String", " "); //returns a pointer to the tokenized string
strtok(NULL, " ");
strtok(NULL, " ");
strtok(NULL, " ");
将字符串拆分为:“ 123:”“ A”“ String”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.