I am writing a program in a linux system where I have to find the newest modified file (ie: the most recent file which has been modified) based on the timestamp in my current directory.
In the example below, I have to look through all the files in the directory and find the one with the latest timestamp (i.e. File.txt).
/root/MyProgram <- Current Directory
-Test1.txt 25/10/2019 14:30:26
-TEST2.bin 15/01/2020 18:12:36
-Test3.bin 06/05/2021 08:45:10
-File.txt 06/12/2021 03:10:55
I am able to get the timestamp of each file in my current directory but I want a method to compare the two timestamps (compare both date and time).
void show_dir_content(char *path) {
struct dirent *dir;
struct stat statbuf;
char datestring[256];
struct tm *tm;
DIR *d = opendir(path);
if (d == NULL) {
return;
}
//
while ((dir = readdir(d)) != NULL) {
if (dir->d_type == DT_REG) {
char f_path[500];
char filename[256];
sprintf(filename, "%s", dir->d_name);
sprintf(f_path, "%s/%s", path, dir->d_name);
printf("filename: %s", filename);
printf(" filepath: %s\n", f_path);
if (stat(f_path, &statbuf) == -1) {
fprintf(stderr,"Error: %s\n", strerror(errno));
continue;
}
tm = gmtime(&statbuf.st_mtime);
time_t t1 = statbuf.st_mtime;
strftime(datestring, sizeof(datestring), " %x-%X", tm);
printf("datestring: %s\n", datestring);
}
if (dir->d_type == DT_DIR && strcmp(dir->d_name, ".") != 0 && strcmp(dir->d_name, "..") != 0) {
printf("directory: %s ", dir->d_name);
char d_path[500];
sprintf(d_path, "%s/%s", path, dir->d_name);
printf(" dirpath: %s\n", d_path);
show_dir_content(d_path);
}
}
closedir(d);
}