每个文件维护了三个时间字段,它们的目的如下表所示:

Field
Description
Example
ls(1) option
st_atime
last-access time of file data
read
-u
st_mtime
last-modification time of file data
write
default
st_ctime
last-change time of i-node status
chmod, chown
-c


第118页的示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
cat  4_21.c 
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.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) {
       printf ( "%s: stat error" , argv[i]);
       continue ;
     }
 
     if  ((fd =  open (argv[i], O_RDWR | O_TRUNC)) < 0) {
       printf ( "%s: open error" , argv[i]);
       continue ;
     }
     close(fd);
 
     timebuf.actime = statbuf.st_atime;
     timebuf.modtime = statbuf.st_mtime;
 
     if  (utime(argv[i], &timebuf) < 0) {
       printf ( "%s: utime error" , argv[i]);
       continue ;
     }
   }
 
   exit (0);
}


运行结果为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
$ gcc -g -o 4_21 4_21.c
 
# 查看最后一次修改的时间
ls  -l foo bar
-rw------- 1 richard richard 0 Dec  4  2014 bar
-rw------- 1 richard richard 0 Dec  4  2014 foo
 
# 查看最后一次访问的时间
ls  -lu foo bar 
-rw------- 1 richard richard 0 Mar 20 20:41 bar
-rw------- 1 richard richard 0 Mar 20 20:41 foo
 
# 打印当前时间
date
Sat Aug 29 13:13:26 CST 2015
 
# 执行程序
$ . /4_21  foo bar
 
# 检查结果
ls  -l foo bar 
-rw------- 1 richard richard 0 Dec  4  2014 bar
-rw------- 1 richard richard 0 Dec  4  2014 foo
 
# 检查最后访问时间
ls  -lu foo bar 
-rw------- 1 richard richard 0 Mar 20 20:41 bar
-rw------- 1 richard richard 0 Mar 20 20:41 foo
 
# 检查最后状态改变时间
ls  -lc foo bar 
-rw------- 1 richard richard 0 Aug 29 13:13 bar
-rw------- 1 richard richard 0 Aug 29 13:13 foo