debian

debian readdir是否支持递归读取

小樊
44
2025-07-29 19:03:26
栏目: 智能运维

readdir 函数本身并不直接支持递归读取目录。它主要用于读取指定目录下的文件和子目录列表。如果你想要递归地读取一个目录及其所有子目录中的文件,你需要自己编写代码来实现这个功能。

以下是一个简单的示例,展示了如何使用 readdir 函数递归地读取目录:

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

void list_files_recursive(const char *path) {
    char full_path[PATH_MAX];
    struct dirent *dp;
    DIR *dir = opendir(path);

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

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

        snprintf(full_path, sizeof(full_path), "%s/%s", path, dp->d_name);

        struct stat path_stat;
        if (stat(full_path, &path_stat) == -1) {
            perror("stat");
            continue;
        }

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

    closedir(dir);
}

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

    list_files_recursive(argv[1]);

    return EXIT_SUCCESS;
}

这个程序接受一个目录路径作为参数,并递归地列出该目录及其所有子目录中的文件。注意,这个示例没有处理符号链接和其他可能的错误情况。在实际应用中,你可能需要根据具体需求进行调整。

0
看了该问题的人还看了