在C語言中,你可以使用readdir函數來讀取目錄中的文件和子目錄。但是,readdir本身并不直接提供文件的修改時間。要獲取文件的修改時間,你需要使用stat函數。
以下是一個簡單的示例,展示了如何使用readdir和stat來獲取目錄中文件的修改時間:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <time.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);
// 獲取文件的狀態信息
if (stat(path, &file_stat) == -1) {
perror("stat");
continue;
}
// 打印文件名和修改時間
char time_buf[26];
ctime_r(&file_stat.st_mtime, time_buf);
time_buf[strcspn(time_buf, "
")] = 0; // 去掉換行符
printf("%s - Modified: %s", entry->d_name, time_buf);
}
// 關閉目錄
closedir(dir);
return EXIT_SUCCESS;
}
這個程序首先打開當前目錄(.),然后使用readdir讀取目錄中的每個條目。對于每個條目,它使用stat函數獲取文件的狀態信息,包括修改時間。然后,它使用ctime_r函數將修改時間轉換為可讀的字符串格式,并打印出來。
注意:ctime_r是線程安全的版本,如果你在一個多線程程序中使用,應該使用這個版本而不是ctime。