13

I have been told by a professor that you can get a file's last modification time by using utime.h. However, the man page seem to cite that utime() only sets this value. How can I look up the last time a file was changed in C on a UNIX system?

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
XBigTK13X
  • 2,655
  • 8
  • 30
  • 39

2 Answers2

13

This returns the file's mtime, the "time of last data modification". Note that Unix also has a concept ctime, the "time of last status change" (see also ctime, atime, mtime).

#include <sys/types.h>
#include <sys/stat.h>

time_t get_mtime(const char *path)
{
    struct stat statbuf;
    if (stat(path, &statbuf) == -1) {
        perror(path);
        exit(1);
    }
    return statbuf.st_mtime;
}
Fred Foo
  • 355,277
  • 75
  • 744
  • 836
  • @AldySyahdeini `localtime(3)` – Fred Foo Apr 18 '14 at 23:08
  • 1
    This was answered in 2010 but it's 2016 now and nanosecond resolution has been implemented since Linux kernel 2.5.48, POSIX.1-2008 and glibc 2.12. So using `statbuf.st_mtim` to get a `struct timespec` instead of using `statbuf.st_mtime` should work everwhere these days. – josch Jun 23 '16 at 11:48
2

You can use the stat system call to get the last access and modification times.

codaddict
  • 445,704
  • 82
  • 492
  • 529