温馨提示×

ubuntu readdir如何获取访问时间

小樊
33
2025-11-28 06:57:07
栏目: 智能运维

在Ubuntu中,你可以使用readdir函数来读取目录中的文件和子目录。然而,readdir函数本身并不直接提供文件的访问时间。要获取文件的访问时间,你需要使用stat结构体和相关的系统调用。

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

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>

int main(int argc, char *argv[]) {
    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");
            closedir(dir);
            return EXIT_FAILURE;
        }

        // 打印文件的访问时间
        char time_buf[20];
        strftime(time_buf, sizeof(time_buf), "%Y-%m-%d %H:%M:%S", localtime(&file_stat.st_atime));
        printf("File: %s, Access Time: %s\n", entry->d_name, time_buf);
    }

    // 关闭目录
    closedir(dir);

    return EXIT_SUCCESS;
}

这个程序会打开当前目录(.),然后使用readdir读取目录中的每个条目。对于每个条目,它构建文件的完整路径,并使用stat获取文件的stat信息。然后,它从stat结构体中提取访问时间(st_atime),并将其格式化为可读的字符串。

编译并运行这个程序,你会看到类似以下的输出:

File: example.txt, Access Time: 2023-10-01 12:34:56
File: another_file.txt, Access Time: 2023-10-02 09:10:11

这显示了每个文件的访问时间。

0