gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 11:37:35 28 4
gpt4 key购买 nike

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

最佳答案

我在我的系统 (Debian) 上查看了这个。

由于某些原因,st_mtime 被定义为一个宏;定义是 st_mtim

忽略 header 的内容(它们对编译器的意义比对人类读者的意义更大),只需按照文档进行操作即可。 man 2 stat 会告诉您需要包含哪些 header ,至少在我的系统上它显示了一个示例程序。


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

/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 是一个结构,其中包含一个名为 tv_sectime_t 类型的成员。 (其他成员允许更高分辨率的时间戳。)

接下来是以下预处理器指令:

# 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. */

关于c++ - 为什么我的 struct stat 有一个 st_mtim 而不是 st_mtime 字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23944199/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com