I start learning C last week and even the simple tasks can be a challenge for me. Currently I am facing this problem: I have a txt file with many lines, each of them starting with a key word (NMEA format for those who know it):
$GPGGA,***001430.00***,.......
$GPRMC,001430.00,.......
$GPGSV,................ 1st time the message arrives
$GPGSA,................
----------
$GPGGA,***005931.00***,...............
$GPRMC,005931.00,............... last time
$GPGSV,.........................
$GPGSA,.........................
I want to extract the time stamp for the last occurrance of $GPGGA line. Till now I was able just to extract the first and the very last line of the file (unfortunately the last line is not the GPGGA message). I tried to look in the file for the key word $GPGGA and then to sscanf the string from a specific byte and store the value in some variables(hour,min,sec).
Any suggestion would be greatly appreciated. Thank you very much for your time and help.
Here is my code:
entint main(int argc, char **argv) {
FILE *opnmea;
char first[100], last[100]; //first and last time the message arrives
int hour,min;
float sec; // time of observation
char year[4], month[2], day[2]; // date of obs campaign
char time[7];
opnmea = fopen(argv[1], "r");
if (opnmea != NULL ) {
fgets(first, 100, opnmea); // read only first line of the file
if (strstr(first, "$GPGGA") != NULL)
{
sscanf(first + 7, "%2d%2d%f", &hour, &min, &sec);
printf("First arrival of stream: %d%d%f \n", hour, min, sec);
}
fseek(opnmea, 0, SEEK_SET);
while (!feof(opnmea)) {
if (strstr(first, "$GPGGA") != NULL) {
memset(last, 0x00, 100); // clean buffer
fscanf(opnmea, "%s\n", last);
}
}
printf("Last arrival of stream: %s\n", last);
fclose(opnmea);
}
else
{
printf("\nfile %s not found", argv[1]);
}
return 0;
}