所以很有可能這就是爲什麼nine
中的i
未被推回。
底線是,當fscanf
操作由於某種原因失敗時,假定文件指針最終位於何處基本上是不安全的。解決這個問題
的一種方法是使用ftell
和fseek
保存文件指針每個成功的項目,這樣就可以移回正確的文件位置,如果你試圖讀取的是不是成功。
比方說,你必須輸入文件:
one 1 2 3 4 5
nine 9 8 7 6 5
in 3.14159 2.71828
將下面的代碼保存和恢復文件的位置,使你的願望它的工作:
#include <stdio.h>
int main(void) {
char buff[50]; double dbl; size_t pos;
FILE *fin = fopen("inputFile.txt", "r");
while (fscanf(fin, "%s", buff) == 1) {
printf("Got string [%s]\n", buff);
pos = ftell(fin);
while (sscanf(buff, "%lf", &dbl) == 1) {
printf("Got double [%f]\n", dbl);
pos = ftell(fin);
}
fseek(fin, pos, SEEK_SET);
}
fclose(fin);
return 0;
}
通過註釋掉的fseek
,你可以看到類似於你所描述的行爲:
Got string [one]
Got double [1.000000]
Got double [2.000000]
Got double [3.000000]
Got double [4.000000]
Got double [5.000000]
Got string [ne]
Got double [9.000000]
Got double [8.000000]
Got double [7.000000]
Got double [6.000000]
Got double [5.000000]
Got double [3.141590]
Got double [2.718280]
我認爲這個解決方案有點麻煩,因爲它不斷需要撥打ftell
,偶爾還要撥打fseek
才能使其工作。
另一種方式是剛讀一切爲字符串,並決定它是否是一個數字或字符串與sscanf
操作看完後,如下面的代碼(與前面提到的輸入文件):
#include <stdio.h>
int main(void) {
char buff[50]; double dbl;
FILE *fin = fopen("inputFile.txt", "r");
while (fscanf(fin, "%s", buff) == 1) {
if (sscanf(buff, "%lf", &dbl) == 1) {
printf("Got double [%f]\n", dbl);
} else {
printf("Got string [%s]\n", buff);
}
}
fclose(fin);
return 0;
}
這是可行的,因爲浮點值實際上是一個字符串的正確子集(即它沒有嵌入空格)。
兩個以上這些程序的輸出是:
Got string [one]
Got double [1.000000]
Got double [2.000000]
Got double [3.000000]
Got double [4.000000]
Got double [5.000000]
Got string [nine]
Got double [9.000000]
Got double [8.000000]
Got double [7.000000]
Got double [6.000000]
Got double [5.000000]
Got string [in]
Got double [3.141590]
Got double [2.718280]
這基本上是什麼需要的話。
在printf(「%s \ n」,word)中使用'word'前檢查'fscanf(fp,「%s」,word)== 1「的結果值;' – chux
我們可以看到類型單詞a和j的聲明? –
請參閱['while(!feof(file))'總是錯誤](http://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong)獲取有關爲什麼您的外部循環爲錯誤。你需要測試'fscanf()'的結果 - 而不是或者'feof()'的結果,或者測試'fscanf()'的結果通常就足夠了。 –