linux

如何使用readdir获取文件修改时间

小樊
34
2025-06-05 23:51:10
栏目: 编程语言

在C语言中,你可以使用readdir函数来读取目录中的文件和子目录。但是,readdir本身并不直接提供文件的修改时间。要获取文件的修改时间,你需要使用stat函数。

以下是一个简单的示例,展示了如何使用readdirstat来获取目录中文件的修改时间:

#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

0
看了该问题的人还看了