在Linux中,readdir函数用于读取目录中的文件和子目录。当你使用readdir读取目录时,它会返回一个struct dirent结构体数组,其中包含了目录中的每个文件和子目录的信息。struct dirent结构体中的d_mtime字段表示文件或目录的最后修改时间。
d_mtime字段是一个time_t类型的值,它表示自1970年1月1日(UTC)以来的秒数。你可以使用C语言中的ctime库函数将time_t类型的时间戳转换为可读的字符串格式。以下是一个简单的示例:
#include <stdio.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 1;
}
while ((entry = readdir(dir)) != NULL) {
char path[1024];
snprintf(path, sizeof(path), "./%s", entry->d_name);
if (stat(path, &file_stat) == -1) {
perror("stat");
continue;
}
char time_str[100];
ctime_r(&file_stat.st_mtime, time_str);
time_str[strcspn(time_str, "\n")] = 0; // Remove newline character
printf("%s - Last modified: %s", entry->d_name, time_str);
}
closedir(dir);
return 0;
}
这个示例程序会打开当前目录(.),然后使用readdir读取目录中的每个文件和子目录。对于每个条目,我们使用stat函数获取文件的元数据,包括最后修改时间。然后我们使用ctime_r函数将time_t类型的时间戳转换为可读的字符串格式,并打印出来。