温馨提示×

Linux readdir时间戳处理

小樊
46
2025-12-03 12:38:00
栏目: 智能运维

在Linux中,readdir函数用于读取目录中的文件和子目录

以下是一个简单的示例,展示了如何使用readdir函数读取目录并处理时间戳:

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

int main(int argc, char *argv[]) {
    DIR *dir;
    struct dirent *entry;
    struct stat file_stat;

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

    dir = opendir(argv[1]);
    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/%s", argv[1], entry->d_name);

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

        // 处理时间戳
        char time_buf[20];
        strftime(time_buf, sizeof(time_buf), "%Y-%m-%d %H:%M:%S", localtime(&file_stat.st_mtime));
        printf("%s: %s\n", entry->d_name, time_buf);
    }

    closedir(dir);
    return EXIT_SUCCESS;
}

这个程序接受一个目录作为命令行参数,然后使用readdir函数读取目录中的所有文件和子目录。对于每个条目,它使用stat函数获取文件的状态信息,包括修改时间戳(st_mtime)。然后,它使用strftime函数将时间戳格式化为易读的字符串,并将其打印到屏幕上。

编译并运行此程序,您将看到类似以下的输出:

file1.txt: 2022-01-01 12:34:56
file2.txt: 2022-01-02 12:34:56
subdir: 2022-01-03 12:34:56

这显示了目录中每个文件的名称及其最后修改时间。

0