Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the last modified date of a file in C

I want to get the last modified date of a file in C. Almost all sources I found use something along this snippet:

char *get_last_modified(char *file) {
    struct tm *clock;
    struct stat attr;

    stat(file, &attr);
    clock = gmtime(&(attr.st_mtime));

    return asctime(clock);
}

But the attr doesn't even have a field st_mtime, only st_mtimespec. Yet, when using this my Eclipse tells me that passing argument 1 of 'gmtime' from incompatible pointer type on the line clock = gmtime(&(attr.st_mtimespec));

What am I doing wrong?

PS: I'm developing on OSX Snow Leopard, Eclipse CDT and using GCC as Cross-Platform compiler

like image 629
F.P Avatar asked Jul 07 '12 08:07

F.P


1 Answers

On OS X, st_mtimespec.tv_sec is the equivalent of st_mtime.

To make this portable, do

#ifdef __APPLE__
#ifndef st_mtime
#define st_mtime st_mtimespec.tv_sec
#endif
#endif

and then use st_mtime.

like image 129
mpartel Avatar answered Sep 17 '22 19:09

mpartel