温馨提示×

debian copendir可用于递归吗

小樊
34
2026-09-16 03:38:42
栏目: 智能运维

在 Debian(以及其它 Linux 系统)里,opendir() 本身不能递归,它只能打开一个目录,返回一个 DIR *,供你用 readdir() 读取该目录下的条目。

关键点

  • opendir()只打开一层目录
  • readdir():读取目录项(文件 / 子目录)
  • 递归必须你自己写代码

典型递归思路(C 语言)

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

void list_dir(const char *path) {
    DIR *dir = opendir(path);
    if (!dir) return;

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

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

        struct stat st;
        stat(full, &st);

        if (S_ISDIR(st.st_mode)) {
            printf("目录: %s\n", full);
            list_dir(full);   // 递归
        } else {
            printf("文件: %s\n", full);
        }
    }
    closedir(dir);
}

如果你不想手写递归

  • 命令行find /path -type d
  • 高级语言
    • C++:std::filesystem::recursive_directory_iterator
    • Python:os.walk()
    • Shell:ls -R

总结

opendir() 是递归遍历的基础工具
❌ 但它不具备递归能力
✅ 递归逻辑必须由程序员实现

如果你是在写 C / C++ 程序,或者想用某个具体语言实现递归目录遍历,可以告诉我。

0