当我读这个文件时,我怎么能读取所有记录

时间:2012-03-14 02:11:23

标签: c file file-io

当我读取文件时,它不包括最后一条记录,所以在这种情况下Bill Biking不显示

以下是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;
}

1 个答案:

答案 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。