readdir
函數本身并不直接提供文件的修改時間。它主要用于讀取目錄中的文件和子目錄。但是,你可以結合其他函數來獲取文件的修改時間。以下是一個使用 C 語言的示例,展示了如何使用 opendir
、readdir
和 stat
函數來獲取目錄中文件的修改時間:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.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 file_path[1024];
snprintf(file_path, sizeof(file_path), "./%s", entry->d_name);
// 獲取文件的 stat 信息
if (stat(file_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;
}
這個示例程序首先打開當前目錄,然后使用 readdir
函數讀取目錄中的每個條目。對于每個條目,它使用 stat
函數獲取文件的元數據,包括修改時間(st_mtime
)。最后,它打印文件名和修改時間。