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);
utimes() is probably how to do it. utime() is obsolete.
Things like this are trivial to determine using tools like strace.
strace touch -t 01010911 xxx
.
.
open("xxx", O_WRONLY|O_NONBLOCK|O_CREAT|O_NOCTTY|O_LARGEFILE, 0666) = 0
utimes("/proc/self/fd/0", {1230829860, 0}) = 0
utimensat()
is the newest version which allows for a timespec
(nanoseconds precision), just like stat(2)
returns (see st_mtim
opposed to st_mtime
—notice the last letter difference). troglobit has the right answer.
Commented
May 13, 2023 at 17:36
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.
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.
AT_FDCWD
if path is relative and the third argument can be NULL
, at least on GLIBC systems, and will then default to the current time, like touch(1)
Commented
Jul 30, 2017 at 9:56