13

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

4 Answers 4

14

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
4
  • I believe strace is Linux-specific and the OP did not mention which UNIX he used (Solaris, FreeBSD, etc, have similar commands but not strace).
    – bortzmeyer
    Commented Mar 16, 2009 at 22:13
  • Oddly, POSIX marks utimes() as legacy, even though it provides more functionality than utime() Commented Mar 17, 2009 at 5:07
  • 2
    @Chris Not anymore. According to Issue 7 "The LEGACY marking is removed.". Source: pubs.opengroup.org/onlinepubs/9699919799/functions/…
    – Alexandros
    Commented May 10, 2016 at 7:57
  • 1
    Note that 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
10

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.

7

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.

2
  • 1
    This answer is almost correct, but instead of 0 as the first argument one should use AT_FDCWD. Also, the third argument is an array of 2 timespec structs.
    – Sven
    Commented Jul 28, 2017 at 14:52
  • 1
    It is of course always a good idea to read the manual to a command you've never used before instead of just cut-and-paste. The first argument should be 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)
    – troglobit
    Commented Jul 30, 2017 at 9:56
1

I think you need to look at the utime()/utimes() system call.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.