#include <stdio.h>
#include <string.h>
#define MAXC 1024
#define MAXDT 16
int main (int argc, char **argv) {
char datestr[MAXDT];
unsigned dateval;
char buf[MAXC];
FILE * fp = fopen("file.csv", "r");
if (!fp) {
perror ("file open failed");
return 1;
}
while (fgets (buf, MAXC, fp)) {
unsigned mo, day, yr;
char *p = strrchr (buf, ','), tmpstr[MAXDT] = "";
unsigned tmpu = 0;
if (!p)
continue;
if(sscanf(p + 1, "%u-%u-%4u", &day, &mo, &yr)!= 3)
continue;
sprintf(tmpstr, "%04u%02u%02u", yr, mo, day);
if(sscanf(tmpstr, "%u", &tmpu) != 1)
continue;
if(tmpu > dateval){
dateval = tmpu;
strcpy(datestr, p + 1);
datestr[strcspn (datestr, "\n")] = 0;
}
}
if (fp != stdin)
fclose (fp);
printf ("last date in file: %s\n", datestr);
}
What I have tried:
In this code, I'm getting the file data and printing the latest date from it. What if there are two files and I want to read both files at the same. Will I have to use
fgets() to read and repeat all the code again or is there any short method that is to read both files and print their data at the same time?