十四、文件和目录——文件时间和utime函数

14.1 文件时间

  存在于 stat 结构体中

  

14.2 文件时间函数

14.2.1 介绍

  utime(修改文件的存取时间和更改时间)
  相关函数 utimes,stat

1 #include <sys/types.h>
2 #include <utime.h>
3 int utime(const char * filename, struct utimbuf * buf);
  • 函数功能
    • 更改文件的存取和修改时间
    • utime 会自动更新 st_ctime 的值
  • 参数 buf
    • 空指针:则取当前时间
      • 进程的有效用户 ID 必须等于该文件的所有者ID
      • 或者进程对该文件具有写权限
    • 非空:取 utimebuf 结构体中的时间
      • 进程有效用户ID 等于该文件的所有者ID
      • 或者进程是超级用户进程    
  • 返回值
    • 如果参数buf为空指针(NULL),则该文件的存取时间和更改时间全部会设为目前时间。
    • 执行成功则返回 0,失败返回-1,错误代码存于errno。
  • 错误代码
    • EACCESS 存取文件时被拒绝,权限不足
    • ENOENT 指定的文件不存在。
1 结构体 utimbuf 定义如下
2 struct utimbuf{
3     time_t actime;  //访问时间
4     time_t modtime;  //修改时间
5 };

14.2.3 例子

  file_time.c

 1 #include <time.h>
 2 #include <sys/types.h>
 3 #include <utime.h>
 4 #include <stdio.h>
 5 #include <stdlib.h>
 6 #include <errno.h>
 7 #include <sys/stat.h>
 8 #include <fcntl.h>
 9 #include <string.h>
10 #include <unistd.h>
11 #include <memory.h>
12 
13 // ctime 函数 将事件转换成字符串输出
14 void out(struct stat buff)
15 {
16     time_t val_atime = (time_t)buff.st_atime;
17     time_t val_mtime = (time_t)buff.st_mtime;
18     time_t val_ctime = (time_t)buff.st_ctime;
19     printf("atime: %s
", ctime(&val_atime));
20     printf("mtime: %s
", ctime(&val_mtime));
21     printf("ctime: %s
", ctime(&val_ctime));
22 }
23 
24 //获取文件属性信息
25 struct stat get_stat(char *file, struct stat buff)
26 {
27     memset(&buff, 0, sizeof(buff));
28     if(lstat(file, &buff) < 0) {
29         perror("lstat error");
30         exit(1);
31     }
32 
33     return buff;
34 }
35 
36 int main(int argc, char *argv[])
37 {
38     if(argc < 2) {
39         fprintf(stderr, "usage:%s file
", argv[0]);
40         exit(1);
41     }
42 
43     struct stat buff;
44     buff = get_stat(argv[1], buff);
45 
46     //备份原先的时间
47     struct stat bak_stat = buff;
48     out(buff);
49     printf("=============================
");
50 
51     //设置文件的事件为当前系统时间
52     utime(argv[1], NULL);
53     buff = get_stat(argv[1], buff);
54     out(buff);
55     printf("=============================
");
56 
57     //把文件的时间恢复成之前的时间
58     struct utimbuf timebuf;
59     timebuf.actime = bak_stat.st_atime;
60     timebuf.modtime = bak_stat.st_mtime;
61     utime(argv[1], &timebuf);
62     buff = get_stat(argv[1], buff);
63     out(buff);
64 
65     return 0;
66 }

  编译执行:

  

  ctime 的时间是 i 节点的最后更改时间,只要调用了 utime 就会自动修改  ctime。

原文地址:https://www.cnblogs.com/kele-dad/p/9065306.html