温馨提示×

ubuntu copendir可以递归子目录吗

小樊
45
2026-09-11 13:52:53
栏目: 智能运维

在 Ubuntu(Linux)下,opendir 本身不能递归子目录。

说明

  • opendir() 只是打开一个目录流,返回一个 DIR *,用于读取当前目录下的条目(文件和子目录名)。
  • 它不会自动进入子目录。
  • 要递归遍历子目录,需要你在代码里:
    1. 用 readdir() 读取目录项
    2. 判断 d_type == DT_DIR
    3. 对子目录再次调用 opendir()

示例(C 语言递归遍历)

#include <stdio.h>
#include <dirent.h>
#include <string.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);
        printf("%s\n", full);

        if (entry->d_type == DT_DIR)
            list_dir(full);
    }
    closedir(dir);
}

int main() {
    list_dir(".");
    return 0;
}

补充说明

  • opendir 属于 POSIX 标准,Linux / Ubuntu 都支持
  • 若想“更方便”地递归,可用:
    • nftw()(标准库)
    • ftw()(较旧)
    • shell 命令:find

总结

✅ opendir 只能打开单层目录
❌ 不能递归
✅ 递归必须自己写逻辑或用其他接口

如果你是想在 shell / Python / C++ 里递归目录,也可以告诉我。

0 踩