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

mow*_*ker 2 c c++ unix linux

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

Kei*_*son 6

我在我的系统(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.  */
Run Code Online (Sandbox Code Playgroud)

A 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
Run Code Online (Sandbox Code Playgroud)

所以你可以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.  */
Run Code Online (Sandbox Code Playgroud)