centos

readdir在CentOS中的递归实现

小樊
39
2025-08-14 20:01:44
栏目: 智能运维

在 CentOS 中,readdir 函数通常用于读取目录的内容。如果你想要递归地读取一个目录及其所有子目录的内容,你需要自己实现这个逻辑。下面是一个简单的示例,展示了如何使用 readdir 函数递归地遍历目录:

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

void list_directory_contents(const char *path);

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

    list_directory_contents(argv[1]);
    return EXIT_SUCCESS;
}

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

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

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

        char full_path[PATH_MAX];
        snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);

        if (lstat(full_path, &statbuf) == -1) {
            perror("lstat");
            continue;
        }

        if (S_ISDIR(statbuf.st_mode)) {
            printf("Directory: %s\n", full_path);
            list_directory_contents(full_path); // Recursive call for subdirectory
        } else {
            printf("File: %s\n", full_path);
        }
    }

    closedir(dir);
}

说明:

  1. list_directory_contents 函数:这个函数接受一个路径作为参数,并打开该路径下的目录。它使用 readdir 来读取目录中的每个条目。

  2. 路径拼接:对于每个目录项,我们构建其完整路径,以便后续调用 lstat 来获取文件的状态信息。

  3. 递归处理:如果一个目录项是一个子目录(通过 S_ISDIR 检查),我们递归调用 list_directory_contents 来处理这个子目录。

  4. 错误处理:在打开目录、获取状态信息和构建路径时,我们都进行了错误检查,并在出错时打印相应的错误信息。

  5. 主函数:程序的入口点接受一个命令行参数作为要遍历的目录路径。

编译和运行:

你可以使用以下命令编译这个程序:

gcc -o listdir_recursive listdir_recursive.c

然后运行它:

./listdir_recursive /path/to/directory

这将递归地列出指定目录及其所有子目录中的文件和目录。

0
看了该问题的人还看了