[英]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.