如何在 Linux 中获取文件创建日期?

新手上路,请多包涵

我正在处理一批文件,这些文件包含同一对象在其生命的不同时期的信息,唯一排序它们的方法是按创建日期。我正在使用这个:

 //char* buffer has the name of file
struct stat buf;
FILE *tf;
tf = fopen(buffer,"r");
//check handle
fstat(tf, &buf);
fclose(tf);
pMyObj->lastchanged=buf.st_mtime;

但这似乎不起作用。我究竟做错了什么?还有其他更可靠/更简单的方法来获取 Linux 下的文件创建日期吗?

原文由 Srv19 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 958
2 个回答

fstat 适用于文件描述符,而不是 FILE 结构。最简单的版本:

 #include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>

#ifdef HAVE_ST_BIRTHTIME
#define birthtime(x) x.st_birthtime
#else
#define birthtime(x) x.st_ctime
#endif

int main(int argc, char *argv[])
{
        struct stat st;
        size_t i;

        for( i=1; i<argc; i++ )
        {
                if( stat(argv[i], &st) != 0 )
                        perror(argv[i]);
                printf("%i\n", birthtime(st));
        }

        return 0;
}

您需要通过检查 sys/stat.h 或使用某种 autoconf 构造来确定您的系统在其 stat 结构中是否有 st_birthtime。

原文由 Mel 发布,翻译遵循 CC BY-SA 3.0 许可协议

最接近“创建日期”的近似值是 --- 中的 struct stat st_ctime 成员,但这实际上记录了 inode 上次更改的时间。如果您创建文件并且从不修改其大小或权限,则作为创建时间。否则,至少在标准 Unix 系统中,没有文件创建时间的记录。

出于您的目的,按 st_mtime 排序或获取名称中带有时间戳的文件。


请注意,如果您使用的是 Darwin (Mac OS X),则可以使用创建时间。从 stat(2) 的手册页中:

然而,当宏 _DARWIN_FEATURE_64_BIT_INODE 被定义时,stat结构现在将被定义为:

  struct stat { /* when _DARWIN_FEATURE_64_BIT_INODE is defined */
     dev_t           st_dev;           /* ID of device containing file */
     mode_t          st_mode;          /* Mode of file (see below) */
     nlink_t         st_nlink;         /* Number of hard links */
     ino_t           st_ino;           /* File serial number */
     uid_t           st_uid;           /* User ID of the file */
     gid_t           st_gid;           /* Group ID of the file */
     dev_t           st_rdev;          /* Device ID */
     struct timespec st_atimespec;     /* time of last access */
     struct timespec st_mtimespec;     /* time of last data modification */
     struct timespec st_ctimespec;     /* time of last status change */
     struct timespec st_birthtimespec; /* time of file creation(birth) */
     off_t           st_size;          /* file size, in bytes */
     blkcnt_t        st_blocks;        /* blocks allocated for file */
     blksize_t       st_blksize;       /* optimal blocksize for I/O */
     uint32_t        st_flags;         /* user defined flags for file */
     uint32_t        st_gen;           /* file generation number */
     int32_t         st_lspare;        /* RESERVED: DO NOT USE! */
     int64_t         st_qspare[2];     /* RESERVED: DO NOT USE! */
 };

注意 st_birthtimespec 字段。还要注意,所有时间都在 struct timespec 值中,因此存在亚秒级时间( tv_nsec 提供纳秒级分辨率)。 POSIX 2008 <sys/stat.h> 要求 struct timespec 时间保持在标准时间;达尔文紧随其后。

原文由 Jonathan Leffler 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题