I am working on a C program where I need to get the last modified time of the file. What the program does is a function loops through each file within a directory and when a
This worked fine for me:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/stat.h>
#include <sys/types.h>
void getFileCreationTime(char *path) {
struct stat attr;
stat(path, &attr);
printf("Last modified time: %s", ctime(&attr.st_mtime));
}
This is one of those cases where timezones matter. You're getting gmtime of the st_mtime. You should instead be using localtime viz.
strftime(date, 20, "%d-%m-%y", localtime(&(attrib.st_ctime)));
this is because ls uses your timezone information, and when you used gmtime as part of the display, it deliberately omitted any timezone information.
Things to fix:
st_ctime.stat() succeeds before using its result.strftime(date, sizeof date, ... to remove the risk of using the wrong buffer size.I first suspected that your filesystem simply didn't support tracking the last-modified time, but since you say that other tools manage to show it, I suspect the code is breaking for whatever reason.
Could it be that the filenames are not full path names, i.e. they don't include the proper directory prefix?