Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write file modification dates programmatically in POSIX?

Tags:

c

file

unix

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);

Thank you for help.

like image 651
Janis Veinbergs Avatar asked Mar 16 '09 18:03

Janis Veinbergs


People also ask

Which command is used to update modification date for any file?

The touch command changes certain dates for each file argument. By default, touch sets both the date of last file modification and the date of last file access to the current time.

What is modification timestamp?

The modified timestamp contains the time the file's data has been changed. It means when we make changes to the actual contents of the file, the file system will update the modification time.


1 Answers

The old utime() and utimes() are OK for many use-cases, but to update atime & mtime with nanosecond resolution, which you need on modern systems, use:

utimensat(0, path, NULL, 0);

This is very useful in combination with newer stat() which returns a struct timespec st_mtim field in struct stat with nanosecond resolution as well.

like image 154
troglobit Avatar answered Oct 11 '22 13:10

troglobit