温馨提示×

Linux readdir如何获取访问时间

小樊
35
2026-01-05 20:53:28
栏目: 智能运维

在Linux系统中,readdir函数用于读取目录中的条目。但是,readdir本身并不直接提供文件的访问时间。要获取文件的访问时间,你需要使用其他方法。

一种方法是使用stat结构体和stat函数。以下是一个简单的示例,展示了如何使用stat函数获取文件的访问时间:

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

int main(int argc, char *argv[]) {
    if (argc != 2) {
        fprintf(stderr, "Usage: %s <filename>\n", argv[0]);
        return 1;
    }

    struct stat file_stat;
    if (stat(argv[1], &file_stat) == -1) {
        perror("stat");
        return 1;
    }

    printf("Access time: %s", ctime(&file_stat.st_atime));
    return 0;
}

在这个示例中,我们首先使用stat函数获取文件的状态信息,并将其存储在file_stat结构体中。然后,我们使用ctime函数将访问时间(st_atime)转换为可读的字符串格式,并将其打印出来。

请注意,这个示例仅适用于单个文件。如果你需要遍历目录并获取其中所有文件的访问时间,你可以结合使用opendirreaddirstat函数。以下是一个简单的示例:

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

int main(int argc, char *argv[]) {
    if (argc != 2) {
        fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
        return 1;
    }

    DIR *dir = opendir(argv[1]);
    if (dir == NULL) {
        perror("opendir");
        return 1;
    }

    struct dirent *entry;
    while ((entry = readdir(dir)) != NULL) {
        struct stat file_stat;
        char path[PATH_MAX];

        snprintf(path, sizeof(path), "%s/%s", argv[1], entry->d_name);

        if (stat(path, &file_stat) == -1) {
            perror("stat");
            continue;
        }

        printf("%s - Access time: %s", entry->d_name, ctime(&file_stat.st_atime));
    }

    closedir(dir);
    return 0;
}

在这个示例中,我们首先使用opendir函数打开目录,然后使用readdir函数遍历目录中的条目。对于每个条目,我们构建完整的文件路径,并使用stat函数获取文件的状态信息。最后,我们打印文件名和访问时间。

0