2012-08-23 99 views
6

可能重複:
「while(!feof(file))」 is always wrongC時的讀數二進制文件

如果我寫一個數組到輸出文件,我關閉該文件,然後再次打開該文件,並讀到的一切,直到結束文件已達到,雖然文件只包含4個數字,但該程序將讀取並打印5個數字,爲​​什麼?

程序輸出:

a[0] = 4 
a[1] = 7 
a[2] = 12 
a[3] = 34 
a[4] = 34 

save.bin(用十六進制編輯器)

04000000 07000000 0C000000 22000000 

#include <stdio.h> 
#include <stdlib.h> 
#define path "save.bin" 

int main(void) 
{ 
    FILE *f=NULL; 
    int a[]={4,7,12,34},i,n=4,k; 
    f=fopen(path,"wb"); 
    if(f==NULL) 
    { 
    perror("Error"); 
    exit(1); 
    } 
    for(i=0;i<n;i++) // or I could use fwrite(a,sizeof(int),n,f); 
    fwrite(&a[i],sizeof(int),1,f); 
    fclose(f); 
    f=fopen(path,"rb"); 
    if(f==NULL) 
    { 
    perror("Error"); 
    exit(1); 
    } 
    i=0; 
    while(!feof(f)) 
    { 
    fread(&k,sizeof(int),1,f); 
    printf("a[%d] = %d\n",i,k); 
    i++; 
    } 
    printf("\n"); 
    fclose(f); 
    return 0; 
} 
+0

非常感謝! – Cristi

回答

9

feof(fp)只有當您試圖讀取過去文件結束時變成虛假(即非零值)。這應該解釋爲什麼循環輸入比您期望的更多。

documentation

The function feof() tests the end-of-file indicator for the stream 
    pointed to by stream, returning nonzero if it is set. The end-of- 
    file indicator can be cleared only by the function clearerr(). 

而且閱讀帖子:Why is 「while (!feof (file))」 always wrong?

+3

+1用於解釋如何設置feof()。 – hmjd

1
while(!feof(f)) 
{ 
    fread(&k,sizeof(int),1,f); 
    printf("a[%d] = %d\n",i,k); /** THIS ASSUMES fread() WAS SUCCESSFUL. **/ 
    i++; 
} 

檢查文件的末尾呼籲fread()後immedately或檢查返回值fread(),它返回在這種情況下應讀取的項目數1。循環的一種可能的重組:

while(1 == fread(&k,sizeof(int),1,f)) 
{ 
    printf("a[%d] = %d\n",i,k); 
    i++; 
} 

迴路檢測feof()後,確保EOF達到和循環沒有因一些其他的失敗而告終。

1

我有同樣的問題也是如此。試試這個:

i=0; 
    while(true) 
    { 
    fread(&k,sizeof(int),1,f); 
    if(feof(f)) 
     break; 

    printf("a[%d] = %d\n",i,k); 
    i++; 
    } 

顯然feof不會返回true,除非你讀過文件的末尾。在將數組寫入二進制文件時,我所做的事情是先寫大小,以便知道讀取數據時的準確數據量。