簡體   English   中英

從此測試文件中讀取輸入並測試EOF的最佳方法

[英]C best way to read input from this test file and test for EOF

大家好,我是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 ,則是說它返回已讀取的數量,因此,如果未讀取任何內容,則您已到達文件末尾。

不要忘記,您還必須打開要閱讀的文件,並在完成后將其關閉。

暫無
暫無

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

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