Linux/GCC中如何通过系统调用获取文件创建时间?
获取文件创建时间(Birth Time)的方法
传统的stat/fstat系统调用返回的结构体确实只包含访问、修改、状态变更三类时间,但Linux环境下,只要内核版本和文件系统支持,是可以通过扩展接口获取创建时间的,具体方法如下:
1. 使用statx()系统调用(推荐,Linux 4.11+)
Linux 4.11及以后提供了statx()这个专门的扩展系统调用,能直接获取包括创建时间在内的更多文件属性,其中创建时间对应结构体的stx_btime字段。
示例代码:
#include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #include <stdio.h> #include <time.h> int main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr, "Usage: %s <filename>\n", argv[0]); return 1; } struct statx stx; // 调用statx,指定STATX_BTIME标志来获取创建时间 int ret = statx(AT_FDCWD, argv[1], AT_SYMLINK_NOFOLLOW, STATX_BTIME, &stx); if (ret == -1) { perror("statx failed"); return 1; } // 转换并打印创建时间 printf("Birth time: %s", ctime(&stx.stx_btime.tv_sec)); return 0; }
编译命令:
gcc -o get_birthtime get_birthtime.c -lrt
(部分新内核版本可能不需要-lrt,但加上能保证兼容性)
2. 使用stat()的扩展字段(兼容Linux 2.6.29~4.10)
在Linux 2.6.29到4.10的版本中,部分支持创建时间的文件系统(如ext4)会通过struct stat的扩展字段st_birthtim提供该信息,但需要定义_GNU_SOURCE宏来启用这个扩展。
示例代码:
#define _GNU_SOURCE #include <sys/stat.h> #include <unistd.h> #include <stdio.h> #include <time.h> int main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr, "Usage: %s <filename>\n", argv[0]); return 1; } struct stat st; int ret = stat(argv[1], &st); if (ret == -1) { perror("stat failed"); return 1; } printf("Birth time: %s", ctime(&st.st_birthtim.tv_sec)); return 0; }
重要注意事项
- 文件系统限制:只有ext4、Btrfs、XFS等较新的文件系统支持存储创建时间,ext3及更早的文件系统没有这个属性,调用后会返回无效值。
- 内核版本依赖:上述两种方法分别对应不同的内核版本区间,使用前要确认目标环境的内核版本。
- 跨平台问题:这种获取创建时间的方式是Linux特有的,Windows、BSD等系统有各自的实现逻辑,不能直接复用。
内容的提问来源于stack exchange,提问作者tahzibi.jafar
相关产品推荐
相关产品推荐

