【问题标题】:Why does my struct stat have a st_mtim instead of st_mtime field?为什么我的 struct stat 有一个 st_mtim 而不是 st_mtime 字段?
【发布时间】:2014-05-29 22:42:07
【问题描述】:

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

【问题讨论】:

  • 你有什么版本/发行版的 Linux 和 C++?
  • 他们是否根据文档在做不同的事情?还是错字?

标签: c++ c linux unix


【解决方案1】:

我在我的系统 (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.  */

【讨论】:

    【解决方案2】:

    在我的 Distro (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 字段——所以只需按照记录使用它,或者如果你想做得比秒更好,请使用完整的计时器分辨率...... .

    【讨论】:

      猜你喜欢
      • 2012-08-29
      • 2012-05-06
      • 2017-01-14
      • 1970-01-01
      • 2021-02-26
      • 2014-01-06
      • 1970-01-01
      • 1970-01-01
      • 2016-10-03
      相关资源
      最近更新 更多