Stuart's Useful C/C++ Pages

How do I get the date a file was last modified?

I wanted to be able to use the date that a file was last modified, to set the filename of another file. It took me quite a while to find out how to get hold of the date and it turns out that there are three dates on UNIX/Linux. You can use the stat() function.

#include <sys/stat.h>
#include <unistd.h>
#include <time.h>

struct tm* clock; // create a time structure
struct stat attrib; // create a file attribute structure
stat("afile.txt", &attrib); // get the attributes of afile.txt
clock = gmtime(&(attrib.st_mtime)); // Get the last modified time and put it into the time structure

// clock->tm_year returns the year (since 1900)
// clock->tm_mon returns the month (January = 0)
// clock->tm_mday returns the day of the month