我正在处理一批文件,这些文件包含同一对象在其生命周期不同时间的信息,对它们进行排序的唯一方法是按创建日期。
我正在使用这个:
//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)
:
然而,当宏_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> http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sys_stat.h.html#tag_13_62需要struct timespec
遵守标准时间;达尔文也遵循这一点。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)