为什么我的struct stat有一个st_mtim而不是st_mtime字段?

Why does my struct stat have a st_mtim instead of st_mtime field?

本文关键字:st mtime 字段 mtim stat 有一个 我的 为什么 struct      更新时间:2023-10-16

对于我的计算机科学课程,我们正在C程序中实现"ls"功能,并且需要使用st_mtime字段。然而,当我使用struct stat时,它只有一个st_mtime字段,而不是我需要的st_mtime字段。这与我在/usr/include/sys/stat.h.中的头文件中看到的内容相匹配我怎么能得到结构定义有我需要的领域?

我在我的系统(Debian)上看了一下。

由于某种原因,st_mtime被定义为宏;定义为st_mtim

忽略头文件的内容(它们对编译器的意义大于对人类读者的意义),并遵循文档。man 2 stat会告诉你需要包括哪些头文件,至少在我的系统上它会显示一个示例程序。


血淋淋的细节(你不需要知道它的正确使用):

/usr/include/bits/stat.h中,类型struct stat由以下成员(以及其他成员)定义:

struct timespec st_atim;        /* Time of last access.  */
struct timespec st_mtim;        /* Time of last modification.  */
struct timespec st_ctim;        /* Time of last status change.  */

struct timespec是一个包含time_t类型成员tv_sec的结构体。(其他成员允许更高分辨率的时间戳)

后面跟着以下预处理指令:

# define st_atime st_atim.tv_sec
# define st_mtime st_mtim.tv_sec
# define st_ctime st_ctim.tv_sec

因此,您可以在自己的代码中引用foo.st_mtime,它将扩展为foo.st_mtim.tv_sec,这是您需要的time_t对象。

:

st_atim等的声明之前(在我当前的Ubuntu 18.04系统上)有这个注释:

/* Nanosecond resolution timestamps are stored in a format
   equivalent to 'struct timespec'.  This is the type used
   whenever possible but the Unix namespace rules do not allow the
   identifier 'timespec' to appear in the <sys/stat.h> header.
   Therefore we have to handle the use of this header in strictly
   standard-compliant sources special.  */

在我的发行版(Fedora)上,st_time被定义为一个宏,如下所示,修改时间包括使用struct timespec

修改时间的纳秒。
$ grep -R st_mtim  /usr/include
....
/usr/include/bits/stat.h:    struct timespec st_mtim /* Time of last modification.  */
/usr/include/bits/stat.h:# define st_mtime st_mtim.tv_sec
....

宏是为了与man fstat中记录的st_time字段向后兼容而做的,因此只需按照文档使用它,或者如果您想做得比秒更好,则使用完整的计时器分辨率....