Hey everyone im very new to the C programming language and i am trying to read from a simple .txt file which contains this information:
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
currently i am using fscaf to read in the whole line then store them in correct variables in my structure. I looked up online and it seems that checking for EOF isnt as straight forward as it seems using fscanf as you it returns the amount of "items" read.
Using my below code and the above file:
1) which is the best way to read and store the information from the file in the correct place
2) the best way to check for EOF so it stops and the end of file/doesnt read empty files.
Header file:
#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);
}
}
So I would suggest using fgets
it will read from a file line by line, and return NULL when there is nothing left to read. If everything in your case is on the same line I would probably stick with fscanf
, but you could also use strtok
and read in the whole line and then parse through it using strtok
Take a look here for some more info: http://www.tutorialspoint.com/c_standard_library/c_function_fgets.htm
If you were looking to use fscanf
you were saying that it returns the amount that was read, so if nothing was read, then you have reached the end of the file.
Don't forget you also have to open the files that you wish to read and close them when you are done.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.