在C语言中,使用readdir函数遍历目录时,可以通过struct dirent结构体中的d_mtime字段获取文件的最后修改时间。d_mtime字段表示文件的最后修改时间,以自1970年1月1日以来的秒数表示。
以下是一个简单的示例,演示如何使用readdir函数遍历目录并获取文件的最后修改时间:
#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;
}
// 获取文件的stat信息
if (stat(entry->d_name, &file_stat) == -1) {
perror("stat");
continue;
}
// 将最后修改时间转换为可读格式
char time_str[26];
strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", localtime(&file_stat.st_mtime));
printf("文件名: %s, 最后修改时间: %s\n", entry->d_name, time_str);
}
closedir(dir);
return EXIT_SUCCESS;
}
这个示例程序会遍历当前目录下的所有文件和子目录,并输出它们的文件名和最后修改时间。注意,这里使用了stat函数来获取文件的详细信息,因为readdir函数本身并不提供文件的修改时间。