在Linux系统中,readdir
函数用于读取目录中的文件和子目录
然而,在某些情况下,你可能需要更高的时间戳精度。这时,你可以考虑使用stat
函数来获取文件的详细信息,包括纳秒级别的时间戳。stat
函数返回一个struct stat
结构体,其中包含了文件的多个时间戳字段,如st_atime
(访问时间)、st_mtime
(修改时间)和st_ctime
(状态改变时间)。这些字段的类型为time_t
,通常表示自纪元(1970年1月1日)以来的秒数。但是,某些文件系统(如ext4)支持纳秒级别的时间戳,这时time_t
类型会包含纳秒信息。
要使用stat
函数,你需要包含头文件<sys/stat.h>
,并调用stat
函数,传入文件路径和指向struct stat
结构体的指针。示例代码如下:
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
int main() {
struct stat file_stat;
const char *file_path = "example.txt";
if (stat(file_path, &file_stat) == 0) {
printf("Access time: %ld\n", file_stat.st_atime);
printf("Modify time: %ld\n", file_stat.st_mtime);
printf("Change time: %ld\n", file_stat.st_ctime);
} else {
perror("stat");
return 1;
}
return 0;
}
请注意,stat
函数返回的时间戳可能因文件系统和操作系统而异。在使用纳秒级别时间戳时,请确保你的文件系统和操作系统支持这一特性。