在Ubuntu中,你可以使用readdir
函数来读取目录中的文件,但是readdir
本身并不直接提供文件的修改时间。不过,你可以通过stat
结构体来获取文件的修改时间。
以下是一个简单的示例,展示了如何使用readdir
和stat
来获取目录中文件的修改时间:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.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);
// 获取文件的stat信息
if (stat(path, &file_stat) == -1) {
perror("stat");
continue;
}
// 打印文件名和修改时间
printf("File: %s\n", entry->d_name);
printf("Last modified: %s", ctime(&file_stat.st_mtime));
}
// 关闭目录
closedir(dir);
return EXIT_SUCCESS;
}
在这个示例中,我们首先使用opendir
函数打开当前目录(.
),然后使用readdir
函数读取目录中的每个条目。对于每个条目,我们使用snprintf
构建文件的完整路径,并使用stat
函数获取文件的stat
信息。stat
结构体中的st_mtime
字段包含了文件的最后修改时间。
注意,ctime
函数将时间戳转换为本地时间的字符串表示形式。如果你需要UTC时间,可以使用ctime_r
函数和gmtime_r
函数。
编译并运行这个程序,你将看到目录中每个文件的名称和最后修改时间。