我已经用谷歌搜索了大约两个小时,但我找不到任何有用的答案。
联机帮助页中指定的“stat”定义表明存在 st_ctime 字段。
struct stat { dev_t st_dev; /* ID of device containing file */ ino_t st_ino; /* inode number */ mode_t st_mode; /* protection */ nlink_t st_nlink; /* number of hard links */ uid_t st_uid; /* user ID of owner */ gid_t st_gid; /* group ID of owner */ dev_t st_rdev; /* device ID (if special file) */ off_t st_size; /* total size, in bytes */ blksize_t st_blksize; /* blocksize for file system I/O */ blkcnt_t st_blocks; /* number of 512B blocks allocated */ time_t st_atime; /* time of last access */ time_t st_mtime; /* time of last modification */ time_t st_ctime; /* time of last status change */ };
但是,即使我使用的是 gcc(其行为应该符合标准),这对我的系统来说似乎并非如此。
事实上,所有时间字段(atime、mtime、ctime)都丢失了,因此该结构包含一些 atim、mtim 和 ctim 值,它们返回 timespec 而不是所需的 time_t 值。
现在我的问题:
- 为什么会这样?也许我包含了错误的 header ,但我真的确定它一定是 sys/stat.h。
- 我没有找到太多关于 timespec 的信息,它是什么以及为什么返回这里?
- 即使我找到了解决方法,它对我有帮助吗?或者其他系统是否会无法执行我的代码?
我正在使用 Ubuntu 11.10 和 gcc 4.6.1。
我的代码(部分):
struct stat file_info;
time_t t;
if( lstat( path, &file_info ) == 0 ) {
struct tm* timeinfo;
t = file_info.st_ctime;
timeinfo = localtime( &t );
如果你能在这方面提供帮助,我真的很高兴,我真的不知道为什么我不能使用我的结构的 st_ctime 字段进行编译,而且像往常一样,gcc 在谈论时并没有太多帮助关于错误 ;-)
可能它与#include 问题有关,但我无法确定是什么。
最佳答案
POSIX 2008 要求 stat() 返回 struct timespec,以便时间戳的小数部分可用于提高时间戳的精度——一秒的分辨率对于文件时间来说是不够的。
添加:
来自 man page
从内核 2.5.48 开始,stat 结构支持三个文件时间戳字段的纳秒分辨率。如果定义了 _BSD_SOURCE 或 _SVID_SOURCE 功能测试宏,Glibc 使用 st_atim.tv_nsec 形式的名称公开每个字段的纳秒分量。这些字段在 POSIX.1-2008 中指定,并且从 2.12 版开始,如果 _POSIX_C_SOURCE 定义为 200809L 或更大的值,或者 _XOPEN_SOURCE 定义为 700 或更大的值,glibc 也会公开这些字段名称。如果上述宏均未定义,则纳秒值将以 st_atimensec 形式的名称公开。在不支持亚秒时间戳的文件系统上,纳秒字段返回值为 0。
关于C stat 结构没有 st_ctime 字段,只有 st_ctim,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8403963/