2014-11-14 57 views
-3

我遇到fread()函數有問題。 我在文件中保存了三個結構(名稱,卷號等),但是當我要讀取整個結構時,它只顯示我已保存的最後一個結構。它是否有任何兼容性問題或有解決方案?使其變爲的邏輯是:用fread讀取文件,但無法正常工作

void rfile() 
{ 
    clrscr(); 
    int n=0; 
    FILE *fptr; 
    if ((fptr=fopen("test2.rec","rb"))==NULL) 
    printf("\nCan't open file test.rec.\n"); 
    else 
    { 
    while (fread(&person[n],sizeof(person[n]),1,fptr)!=1); 
    printf("\nAgent #%d.\nName = %s.",n+1,person[n].name); 
    printf("\nIdentification no = %d.",person[n].id); 
    //printf("\nHeight = %.1f.\n",person[n].height); 
    n++; 
    fclose(fptr); 
    printf("\nFile read,total agents is now %d.\n",n); 
    } 
} 
+0

此「void rfile()」是在「main()」中調用的函數。 – 2014-11-14 17:46:47

+0

這是嚴格的CIO,我刪除了C++標記。 – Borgleader 2014-11-14 17:46:58

回答

1

問題是while (fread(&person[n],sizeof(person[n]),1,fptr)!=1);:這會將文件讀到最後。因此,結果是數組中放置的唯一person是該文件的最後一個,它位於n=0。若要更正此問題,請使用大括號在while循環中實際執行某些操作:

void rfile() 
{ 
    clrscr(); 
    int n=0; 
    FILE *fptr; 
    if ((fptr=fopen("test2.rec","rb"))==NULL) 
     printf("\nCan't open file test.rec.\n"); 
    else 
    { 
     while (fread(&person[n],sizeof(person[n]),1,fptr)==1){//here ! 
      printf("\nAgent #%d.\nName = %s.",n+1,person[n].name); 
      printf("\nIdentification no = %d.",person[n].id); 
      //printf("\nHeight = %.1f.\n",person[n].height); 
      n++; 
     }//there ! 
     fclose(fptr); 
     printf("\nFile read,total agents is now %d.\n",n); 
    } 
} 
+0

你是對的!我錯過了這一個!我編輯並更正了它。 – francis 2014-11-14 21:00:55