[英]What is the best way to read input of unpredictable and indeterminate (ie no EOF) size from stdin in C?
[英]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.