2012-03-14 67 views
0

當我閱讀該文件不包括最後的記錄,所以在這種情況下,比爾自行車不露面當我看到這個文件,我怎麼能讀取所有的記錄

這裏是hobbies.dat文件:

Bob Running 
Josh Swimming 
Bill Biking 

而這裏的程序代碼:

#include <stdio.h> 
#include <stdlib.h> 

int main(void) 
{ 
    FILE *fp; 
    char name[30]; 
    char hobby[30]; 

    char *filename = "hobbies.dat"; 
    fp = fopen(filename, "r"); 

    if (fp == NULL) { 
     printf("File cannot open"); 
     perror("The following error has occured"); 
    } 
    else 
    { 
     printf("\nName\tHobby\n\n"); 
     fscanf(fp, "%s%s", name, hobby); 

     while (!feof(fp)) 
     { 
      printf("%s\t%s\n", name, hobby); 
      fscanf(fp, "%s%s", name, hobby); 
     } 
    } 

    system("pause"); 
    return 0; 
} 

回答

0

改變循環如下:

... 
else 
{ 
    printf("\nName\tHobby\n\n"); 
    while (!feof(fp)) 
    { 
     fscanf(fp, "%s%s", name, hobby); 
     printf("%s\t%s\n", name, hobby); 
    } 
} 
... 

我改變了這個,因爲你需要再次在fscanf之前做最後的打印並達到EOF。

+0

非常感謝 – user1251302 2012-03-14 03:37:29

相關問題