在C语言中,你可以使用readdir
函数来读取目录中的文件和子目录。但是,readdir
本身并不直接提供文件的修改时间。要获取文件的修改时间,你需要使用stat
函数。
以下是一个简单的示例,展示了如何使用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 path[PATH_MAX];
snprintf(path, sizeof(path), "./%s", entry->d_name);
// 获取文件的状态信息
if (stat(path, &file_stat) == -1) {
perror("stat");
continue;
}
// 打印文件名和修改时间
char time_buf[26];
ctime_r(&file_stat.st_mtime, time_buf);
time_buf[strcspn(time_buf, "
")] = 0; // 去掉换行符
printf("%s - Modified: %s", entry->d_name, time_buf);
}
// 关闭目录
closedir(dir);
return EXIT_SUCCESS;
}
这个程序首先打开当前目录(.
),然后使用readdir
读取目录中的每个条目。对于每个条目,它使用stat
函数获取文件的状态信息,包括修改时间。然后,它使用ctime_r
函数将修改时间转换为可读的字符串格式,并打印出来。
注意:ctime_r
是线程安全的版本,如果你在一个多线程程序中使用,应该使用这个版本而不是ctime
。