tags:

views:

252

answers:

3

Hello.

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.

+1  A: 

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.

Johannes Weiß
+1  A: 

I think you need to look at the utime()/utimes() system call. Not at my normal computer so I can't look up the details I'm afraid.

Jackson
+7  A: 

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
sigjuice
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
Oddly, POSIX marks utimes() as legacy, even though it provides more functionality than utime()
Chris Young