每个文件维护了三个时间字段,它们的目的如下表所示:
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页的示例代码:
$ 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);
}
运行结果为:
$ 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
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。