【发布时间】:2013-11-15 21:13:09
【问题描述】:
大家好,我对 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);
}
}
【问题讨论】: