在Linux系统中,readdir
函数用于读取目录中的条目。要获取文件的修改时间,你需要结合其他函数来实现。以下是一个使用C语言编写的示例,展示了如何使用readdir
和stat
函数获取目录中文件的修改时间:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.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_buf[20];
strftime(time_buf, sizeof(time_buf), "%Y-%m-%d %H:%M:%S", localtime(&file_stat.st_mtime));
printf("文件名: %s, 修改时间: %s\n", entry->d_name, time_buf);
}
closedir(dir);
return EXIT_SUCCESS;
}
这个示例程序首先打开当前目录,然后使用readdir
函数读取目录中的每个条目。对于每个条目,我们使用stat
函数获取文件的状态信息,包括修改时间。最后,我们将修改时间格式化为易读的字符串并打印出来。
注意:这个示例程序仅适用于类Unix系统,如Linux和macOS。在Windows系统中,你需要使用不同的函数,如FindFirstFile
、FindNextFile
和GetFileTime
。