centos

如何在CentOS中使用readdir实现递归遍历

小樊
46
2025-04-10 19:57:08
栏目: 智能运维

在 CentOS 中,你可以使用 C 语言的 dirent.h 库中的 readdir 函数来实现递归遍历目录

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

void list_directory_contents(const char *path) {
    DIR *dir;
    struct dirent *entry;
    struct stat path_stat;

    dir = opendir(path);
    if (!dir) {
        perror("opendir");
        return;
    }

    while ((entry = readdir(dir)) != NULL) {
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
            continue;
        }

        snprintf(path_stat.path, sizeof(path_stat.path), "%s/%s", path, entry->d_name);
        if (stat(path_stat.path, &path_stat) == -1) {
            perror("stat");
            continue;
        }

        if (S_ISDIR(path_stat.st_mode)) {
            list_directory_contents(path_stat.path);
        } else {
            printf("%s\n", path_stat.path);
        }
    }

    closedir(dir);
}

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

    list_directory_contents(argv[1]);

    return EXIT_SUCCESS;
}

将此代码保存为 recursive_readdir.c,然后使用以下命令编译:

gcc -o recursive_readdir recursive_readdir.c

现在,你可以运行编译后的程序,传递一个目录作为参数,它将递归地列出该目录下的所有文件和子目录:

./recursive_readdir /path/to/directory

请注意,这个示例仅适用于 CentOS 以及其他类 Unix 系统。如果你需要在其他操作系统上实现类似的功能,可能需要进行一些调整。

0
看了该问题的人还看了