Issue
I am working with batches of files that contain information about the same object at the different times of its life, and the only way to order them is by creation date. I was using this:
//char* buffer has the name of file
struct stat buf;
FILE *tf;
tf = fopen(buffer,"r");
//check handle
fstat(tf, &buf);
fclose(tf);
pMyObj->lastchanged=buf.st_mtime;
But that does not seems to work. What am I doing wrong? Are there other, more reliable/simple ways to get file creation date under Linux?
Solution
fstat works on file descriptors, not FILE structures. The simplest version:
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#ifdef HAVE_ST_BIRTHTIME
#define birthtime(x) x.st_birthtime
#else
#define birthtime(x) x.st_ctime
#endif
int main(int argc, char *argv[])
{
struct stat st;
size_t i;
for( i=1; i<argc; i++ )
{
if( stat(argv[i], &st) != 0 )
perror(argv[i]);
printf("%i\n", birthtime(st));
}
return 0;
}
You will need to figure out if your system has st_birthtime in its stat structure by inspecting sys/stat.h or using some kind of autoconf construct.
Answered By - Mel Answer Checked By - Willingham (WPSolving Volunteer)