How to get the latest date when reading from file?

Viewed 68

In this code, I am trying to read the latest date but it is printing the whole data from the file, which I don't want. I tried all the code in the main function and it was working well.

But in the record function, it didn't give me the required result. How to make this working, just to print the latest date from both files.

#include <stdio.h>
#include <string.h>
#define MAXC 1024     
#define MAXDT 16

typedef struct {       
    char datestr[MAXDT];   
    unsigned dateval;
} datestrval;

int record(char *buf){                        
    datestrval max = { .datestr = "" };  
    do{     
      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, "%d", &tmpu) != 1)
        continue;
      if (tmpu > max.dateval) {     
        max.dateval = tmpu;           
        strcpy (max.datestr, p + 1);
        max.datestr[strcspn (max.datestr, "\n")] = 0;
      }
    }while(0);

    printf ("last date in file: %s\n", max.datestr);
    return 0;  }

Main

int main(){
  char string[MAXC];
  FILE * fp = fopen("file.csv", "r");
  FILE * fp1 = fopen("new.csv", "r");

  while (fgets(string, MAXC, fp)) { 
    record(string);
  }
  while(fgets(string, MAXC, fp1)){
    record(string);
  }
}
1 Answers

How can I save the latest date when calling record()?

You can save it in a global variable. Change typedef struct { … } datestrval; to struct { … } max; and delete the line

    datestrval max = { .datestr = "" };

then you don't lose the date information. Move the line

    printf ("last date in file: %s\n", max.datestr);

to the end of main in order to print only one last date.

Related