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)来实现类似的功能。