简体   繁体   English

当我读取此文件时,如何读取所有记录

[英]When I read this file, how can i read all the records

When I read the file it doesn't include the last record, so in this case Bill Biking does not show up 当我读取文件时,它不包含最后一条记录,因此在这种情况下,Bill Biking不会显示

Here is the hobbies.dat file: 这是hobbies.dat文件:

Bob Running
Josh Swimming
Bill Biking

And here's the program's code: 这是程序的代码:

#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;
}

Change the loop as follows: 如下更改循环:

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

I changed this because you need to do your final print before you fscanf again and reach EOF. 我更改了此设置,因为您需要先进行最终打印,然后再再次fscanf并到达EOF。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM