gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 00:08:35 26 4
gpt4 key购买 nike

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

//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 下是否有其他更可靠/更简单的方法来获取文件创建日期?

最佳答案

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

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


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

However, when the macro _DARWIN_FEATURE_64_BIT_INODE is defined, the stat structure will now be defined as:

 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 field 。还要注意,所有时间都在 struct timespec 中。值,因此存在亚秒级计时(tv_nsec 给出纳秒分辨率)。 POSIX 2008 <sys/stat.h> 需要 struct timespec遵守标准时间; Darwin 遵循这一点。

关于c - 如何在 Linux 中获取文件创建日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5929419/

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