readdir
函數本身并不直接提供文件的修改時間。它主要用于讀取目錄中的條目。但是,你可以結合其他函數來獲取文件的修改時間。以下是一個使用 C 語言的示例,展示了如何使用 opendir
、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 file_path[1024];
snprintf(file_path, sizeof(file_path), "./%s", entry->d_name);
// 獲取文件的 stat 信息
if (stat(file_path, &file_stat) == -1) {
perror("stat");
continue;
}
// 將文件修改時間轉換為可讀格式
char time_str[100];
strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", localtime(&file_stat.st_mtime));
printf("File: %s, Modified time: %s\n", entry->d_name, time_str);
}
closedir(dir);
return EXIT_SUCCESS;
}
這個示例程序首先打開當前目錄,然后使用 readdir
函數讀取目錄中的每個條目。對于每個條目,它使用 stat
函數獲取文件的詳細信息,包括修改時間。最后,它將修改時間轉換為可讀的字符串格式并打印出來。
請注意,這個示例使用了 POSIX 標準庫函數,因此它應該在支持 POSIX 的系統(如 Linux 和 macOS)上運行。如果你使用的是 Windows 系統,你需要使用 Windows API 函數(如 FindFirstFile
、FindNextFile
和 GetFileTime
)來實現類似的功能。