大家好,我是C编程语言的新手,我正试图从一个简单的.txt文件中读取该文件,其中包含以下信息:

  13 11 2011 13 10 00 GS452 45 20
  13 11 2011 15 14 23 EI597 60 30
  13 11 2011 15 34 35 EI600 20 15


目前,我正在使用fscaf读取整行,然后将它们存储在结构中的正确变量中。我在网上查了一下,似乎检查EOF并不像使用fscanf那样简单,因为它返回读取的“项目”数量。

使用下面的代码和上面的文件:

1)这是从文件中正确位置读取和存储信息的最佳方法

2)检查EOF的最佳方法,使其停止并且文件结尾/不读取空文件。

头文件:

  #ifndef MAYDAY_STRUCT_H
  #define   MAYDAY_STRUCT_H

  #ifdef    __cplusplus
   extern "C" {
   #endif

typedef struct {
    /* unsigned because these values cannot be negative*/

    unsigned int day;
    unsigned int month;
    unsigned int year;
    unsigned int hour;
    unsigned int mins;
    unsigned int secs;
    char ais[5];
    unsigned int l_boat_time;
    unsigned int heli_time;


} mayday_call;

void read_may_day_file();

#ifdef  __cplusplus
}


main.c

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


 int main(int argc, char** argv) {


read_may_day_file();


return (EXIT_SUCCESS);
 }

void read_may_day_file() {

char locof[30];
char eofTest;
mayday_call mday;



printf("please enter the location of the input file \n");
scanf("%s", locof);

FILE *fp;
fp = fopen(locof, "r");


if (fp) {



        fscanf(fp, "%d %d %d %d %d %d %s %d %d", &mday.day, &mday.month, &mday.year, &mday.hour, &mday.mins, &mday.secs, mday.ais, &mday.l_boat_time, &mday.heli_time);


        printf("reading file mayday_1.txt \n"
                "day %d \n"
                "month %d \n"
                "yr %d \n"
                "hour % d\n"
                "mins %d \n"
                "sec %d \n"
                "ais %s \n"
                "lBoattime %d\n"
                "helitime %d \n", mday.day, mday.month,
                mday.year, mday.hour, mday.mins, mday.secs, mday.ais, mday.l_boat_time, mday.heli_time);

        fclose(fp);
    }

}

最佳答案

因此,我建议使用fgets它将逐行读取文件,并在没有剩余读取内容时返回NULL。如果您遇到的所有情况都在同一行上,我可能会坚持使用fscanf,但是您也可以使用strtok并读取整行,然后使用strtok进行解析

在这里查看更多信息:http://www.tutorialspoint.com/c_standard_library/c_function_fgets.htm

如果要使用fscanf,则是说它返回已读取的数量,因此,如果未读取任何内容,则说明文件已到达末尾。

别忘了,您还必须打开要阅读的文件,并在完成后将其关闭。

关于c - 从此测试文件读取输入并测试EOF的最佳方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20010689/

10-11 22:24
查看更多