在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
函數返回的時間戳可能因文件系統和操作系統而異。在使用納秒級別時間戳時,請確保你的文件系統和操作系統支持這一特性。