文件的时间(UNIX环境高级编程笔记)

  使用4个stat函数可以获得文件相关的信息结构。对每个文件维护3个时间字段。

stat 结构体
struct stat {
  dev_t st_dev; /* ID of device containing file /
  ino_t st_ino; /
inode number /
  mode_t st_mode; /
protection /
  nlink_t st_nlink; /
number of hard links /
  uid_t st_uid; /
user ID of owner /
  gid_t st_gid; /
group ID of owner /
  dev_t st_rdev; /
device ID (if special file) /
  off_t st_size; /
total size, in bytes /
  blksize_t st_blksize; /
blocksize for file system I/O /
  blkcnt_t st_blocks; /
number of 512B blocks allocated /
  time_t st_atime; /
time of last access /
  time_t st_mtime; /
time of last modification /
  time_t st_ctime; /
time of last status change */
};

可以看到在stat结构体中有三个time_t类型的成员,它们的意义如下:

  字段   说明
st_atime 文件数据的最后访问时间
st_mtime 文件数据的最后修改时间
st_ctime i节点状态的最后更改时间

  修改时间(st_mtime)是文件内容的最后一次被修改的时间。状态更改时间(st_ctime)是该文件的i节点最后一次被修改的时间。chmod、chown等更改的是i节点的节点信息,并没有更改文件的实际内容。write等改的是文件的实际内容。
  下图为各函数对访问、修改和状态更改时间的作用:
文件的时间(UNIX环境高级编程笔记)  一个文件的访问和修改时间可以用一下几个函数修改:futimens和utimensat函数可以指定纳秒级精度的时间戳。

#include <sys/stat.h>
int futimens(int fd, const struct timespec times[2]);
int utimensat(int fd, const char *path, const struct timespec times[2], int flag);

  这两个函数的times数组参数的第一个元素包含访问时间,第二元素包含修改时间。这两个时间值是日历时间。
  futimens函数需要打开文件来更改它的时间,utimensat函数提供了一种使用文件名更改时间的方法。

#include <sys/time.h>
int utimes(const char *pathname, const struct timeval times[2])

  utimes函数对路径名进行操作。

struct utimbuf {
  time_t actime; /* access time /
  time_t modtime; /
modification time */
};