在Ubuntu中,你可以使用readdir函數來讀取目錄中的文件,但是readdir本身并不直接提供文件的修改時間。不過,你可以通過stat結構體來獲取文件的修改時間。
以下是一個簡單的示例,展示了如何使用readdir和stat來獲取目錄中文件的修改時間:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
int main() {
DIR *dir;
struct dirent *entry;
struct stat file_stat;
// 打開目錄
dir = opendir(".");
if (dir == NULL) {
perror("opendir");
return EXIT_FAILURE;
}
// 讀取目錄中的文件
while ((entry = readdir(dir)) != NULL) {
// 跳過當前目錄和上級目錄
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
// 構建文件的完整路徑
char path[PATH_MAX];
snprintf(path, sizeof(path), "./%s", entry->d_name);
// 獲取文件的stat信息
if (stat(path, &file_stat) == -1) {
perror("stat");
continue;
}
// 打印文件名和修改時間
printf("File: %s\n", entry->d_name);
printf("Last modified: %s", ctime(&file_stat.st_mtime));
}
// 關閉目錄
closedir(dir);
return EXIT_SUCCESS;
}
在這個示例中,我們首先使用opendir函數打開當前目錄(.),然后使用readdir函數讀取目錄中的每個條目。對于每個條目,我們使用snprintf構建文件的完整路徑,并使用stat函數獲取文件的stat信息。stat結構體中的st_mtime字段包含了文件的最后修改時間。
注意,ctime函數將時間戳轉換為本地時間的字符串表示形式。如果你需要UTC時間,可以使用ctime_r函數和gmtime_r函數。
編譯并運行這個程序,你將看到目錄中每個文件的名稱和最后修改時間。