4.19. utime FunctionThe access time and the modification time of a file can be changed with the utime function.
The structure used by this function is struct utimbuf { time_t actime; /* access time */ time_t modtime; /* modification time */ } The two time values in the structure are calendar times, which count seconds since the Epoch, as described in Section 1.10. The operation of this function, and the privileges required to execute it, depend on whether the times argument is NULL.
Note that we are unable to specify a value for the changed-status time, st_ctimethe time the i-node was last changedas this field is automatically updated when the utime function is called. On some versions of the UNIX System, the touch(1) command uses this function. Also, the standard archive programs, tar(1) and cpio(1), optionally call utime to set the times for a file to the time values saved when the file was archived. ExampleThe program shown in Figure 4.21 truncates files to zero length using the O_TRUNC option of the open function, but does not change their access time or modification time. To do this, the program first obtains the times with the stat function, truncates the file, and then resets the times with the utime function. We can demonstrate the program in Figure 4.21 with the following script: $ ls -l changemod times look at sizes and last-modification times -rwxrwxr-x 1 sar 15019 Nov 18 18:53 changemod -rwxrwxr-x 1 sar 16172 Nov 19 20:05 times $ ls -lu changemod times look at last-access times -rwxrwxr-x 1 sar 15019 Nov 18 18:53 changemod -rwxrwxr-x 1 sar 16172 Nov 19 20:05 times $ date print today's date Thu Jan 22 06:55:17 EST 2004 $ ./a.out changemod times run the program in Figure 4.21 $ ls -l changemod times and check the results -rwxrwxr-x 1 sar 0 Nov 18 18:53 changemod -rwxrwxr-x 1 sar 0 Nov 19 20:05 times $ ls -lu changemod times check the last-access times also -rwxrwxr-x 1 sar 0 Nov 18 18:53 changemod -rwxrwxr-x 1 sar 0 Nov 19 20:05 times $ ls -lc changemod times and the changed-status times -rwxrwxr-x 1 sar 0 Jan 22 06:55 changemod -rwxrwxr-x 1 sar 0 Jan 22 06:55 times As we expect, the last-modification times and the last-access times are not changed. The changed-status times, however, are changed to the time that the program was run. Figure 4.21. Example of utime function#include "apue.h" #include <fcntl.h> #include <utime.h> int main(int argc, char *argv[]) { int i, fd; struct stat statbuf; struct utimbuf timebuf; for (i = 1; i < argc; i++) { if (stat(argv[i], &statbuf) < 0) { /* fetch current times */ err_ret("%s: stat error", argv[i]); continue; } if ((fd = open(argv[i], O_RDWR | O_TRUNC)) < 0) { /* truncate */ err_ret("%s: open error", argv[i]); continue; } close(fd); timebuf.actime = statbuf.st_atime; timebuf.modtime = statbuf.st_mtime; if (utime(argv[i], &timebuf) < 0) { /* reset times */ err_ret("%s: utime error", argv[i]); continue; } } exit(0); } |