cunixfileposix

How do I write file modification dates programmatically in POSIX?


I would like to touch my files from C code to modify their access date. This does not seem to work:

struct stat fileSt;
lstat(path, &fileSt);
fileSt.st_mtime = time(NULL);

Solution

  • I think you want utime(2). That should be enough:

    utime(filename, NULL);
    

    The docs say:

    int utime(const char *filename, const struct utimbuf *times);
    

    [...]

    The utime() system call changes the access and modification times of the inode specified by filename to the actime and modtime fields of times respectively.

    If times is NULL, then the access and modification times of the file are set to the current time.