温馨提示×

readdir如何获取文件最后访问时间

小樊
36
2025-11-27 15:19:49
栏目: 编程语言

在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 file_path[1024];
        snprintf(file_path, sizeof(file_path), "./%s", entry->d_name);

        // 获取文件的stat信息
        if (stat(file_path, &file_stat) == -1) {
            perror("stat");
            continue;
        }

        // 将最后访问时间转换为可读格式并打印
        char time_buf[100];
        strftime(time_buf, sizeof(time_buf), "%Y-%m-%d %H:%M:%S", localtime(&file_stat.st_atime));
        printf("%s: Last accessed time: %s\n", entry->d_name, time_buf);
    }

    closedir(dir);
    return EXIT_SUCCESS;
}

这个程序首先打开当前目录,然后使用readdir函数读取目录中的每个文件。对于每个文件,它使用stat函数获取文件的stat信息,其中包括最后访问时间(st_atime)。然后,它将最后访问时间转换为可读的字符串格式,并将其打印到屏幕上。

0