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?
File creation time is not stored anywhere, you can only retrieve one of the following:
Your code should give you the last modification time, however. Note: you can use
stat()
instead offstat()
without opening the file (stat()
takes the file name as param).fstat works on file descriptors, not FILE structures. The simplest version:
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.
The nearest approximation to 'creation date' is the
st_ctime
member in thestruct stat
, but that actually records the last time the inode changed. If you create the file and never modify its size or permissions, that works as a creation time. Otherwise, there is no record of when the file was created, at least in standard Unix systems.For your purposes, sort by
st_mtime
...or get the files named with a timestamp in the name.Note that if you are on Darwin (Mac OS X), the creation time is available. From the man page for
stat(2)
:Note the
st_birthtimespec
field. Note, too, that all the times are instruct timespec
values, so there is sub-second timing (tv_nsec
gives nanosecond resolution). POSIX 2008<sys/stat.h>
requires thestruct timespec
time keeping on the standard times; Darwin follows that.To get the file creation date in linux, I use the following method
atime: Last time file was opened or executed
ctime: Time the inode information was updated. ctime also gets updated when file is modified
mtime: Last modified time
crtime: File creation time