簡體   English   中英

fgetc 循環返回錯誤結果

[英]fgetc loop returning wrong result

我正在使用 fgetc 和字符計數方法循環遍歷字符文件並以相反的順序返回它們。 當我嘗試這樣做時,發生了兩件意想不到的事情。 當我在第一個循環下面粘貼第二個循環迭代時,它返回一個非常不同的、古怪的結果。 同樣,第一個循環返回正確的結果,除了開頭的一個附加字符。

例如,如果文件包含字符串 'Hello',第一次迭代將返回5olleH和第二次HeHeHeHeHeHeHeHeHeHeHeHeHeHe 兩個循環的正確結果都是olleH

這是代碼:

FILE *file = fopen( argv[1], "r" );    
count = count_characters(file);
int originalCount = count;

while(count){

ch = fgetc(file);
printf("%c", ch);
fseek(file, -2L, 1);   // shifts the pointer to the previous character
count--;

}

count = originalCount;

while(count){

ch = fgetc(file);
printf("%c", ch);
fseek(file, -2L, 1);   // shifts the pointer to the previous character
count--;

}

不清楚 count_characters() 留下了什么狀態。 同樣在第一個循環結束時,您應該位於文件的開頭(實際上在它之前)。 在第二個循環中,您繼續向后移動。

我會設置緩沖區大小並從文件中讀取緩沖區。 對於小文件,閱讀整個內容(您的算法應該考慮小於緩沖區的文件)。 這對我來說似乎更容易。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM