15.01-02 文件时间戳
stat
可以用 stat
族系统调用来获取文件的属性。
utime
秒级时间戳更新
用 utime
族系统调用来设置文件的时间信息。修改时需要有相应的权限,以 utime
为例,其签名为:
int utime(const char *filename,
const struct utimbuf *_Nullable times);
如果 times
参数为 NULL
,则会将文件的 atime 和 mtime 修改为当前的时间。这需要进程的文件系统用户 ID 和文件匹配,且有写权限,或者是带有 CAP_FOWNER
或者 CAP_DAC_OVERRIDE
的特权级程序。
如果 times
参数非空,那么会用给定结构体的信息去更新 atime 和 mtime(ctime 信息是不能用系统调用任意修改的)。这需要进程的文件系统用户 ID 和文件匹配并有写权限,或者是带有 CAP_FOWNER
的特权级程序。
utimes
微秒级时间戳更新
utimes
/ futimes
/ lutimes
也都能更新文件时间,加了 s 表示其参数是 timeval
的数组,也就支持了微秒级别的精度。
utimensat
纳秒级时间戳更新
int utimensat(int dirfd, const char *pathname,
const struct timespec times[_Nullable 2], int flags);
int futimens(int fd, const struct timespec times[_Nullable 2]);
timespec
中的 tv_nsec
字段设置为 UTIME_NOW
可以将时间戳更新为当前时间,设置为 UTIME_OMIT
可以将时间戳保持不变。除了纳秒级时间之外,utimensat
和 futimens
可以独立更新某一个时间(atime 或者 mtime)也是一种改进。