linux

Linux copendir如何获取目录下文件的修改时间

小樊
33
2025-06-18 00:46:06
栏目: 智能运维

在 Linux 中,使用 opendir()readdir() 函数可以遍历目录中的文件。要获取目录下文件的修改时间,可以使用 stat() 函数。以下是一个简单的示例:

#include <stdio.h>
#include <stdlib.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;

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

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

    while ((entry = readdir(dir)) != NULL) {
        // 跳过 "." 和 ".." 目录
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
            continue;
        }

        // 拼接文件路径
        char file_path[PATH_MAX];
        snprintf(file_path, sizeof(file_path), "%s/%s", argv[1], entry->d_name);

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

        // 打印文件名和修改时间
        printf("%s: %s", entry->d_name, ctime(&file_stat.st_mtime));
    }

    closedir(dir);
    return 0;
}

这个程序接受一个目录作为命令行参数,然后遍历该目录下的所有文件(不包括 “.” 和 “…” 目录)。对于每个文件,它使用 stat() 函数获取文件的状态信息,并打印文件名和修改时间。

编译并运行此程序,例如:

gcc get_modification_time.c -o get_modification_time
./get_modification_time /path/to/directory

这将输出指定目录下所有文件的修改时间。

0
看了该问题的人还看了