温馨提示×

Linux readdir如何获取修改时间

小樊
45
2026-01-05 20:52:28
栏目: 智能运维

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

以下是一个使用C语言和dirent.h库的示例,展示了如何使用stat函数获取目录中文件的修改时间:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <dirent.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);

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

        // 将修改时间转换为可读格式
        char time_str[100];
        strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", localtime(&file_stat.st_mtime));

        printf("File: %s\n", entry->d_name);
        printf("Modified time: %s\n", time_str);
    }

    closedir(dir);
    return EXIT_SUCCESS;
}

这个示例程序首先打开当前目录(.),然后使用readdir函数读取目录中的每个条目。对于每个条目,我们使用snprintf构建文件的完整路径,然后使用stat函数获取文件的状态信息。stat结构体中的st_mtime字段包含了文件的修改时间(以秒为单位,自1970年1月1日以来的时间)。最后,我们使用strftime函数将修改时间转换为可读的字符串格式,并将其打印出来。

0