簡體   English   中英

當我讀取此文件時,如何讀取所有記錄

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

當我讀取文件時,它不包含最后一條記錄,因此在這種情況下,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;
}

如下更改循環:

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

我更改了此設置,因為您需要先進行最終打印,然后再再次fscanf並到達EOF。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM