温馨提示×

ubuntu copendir能否递归遍历

小樊
37
2026-09-05 18:18:15
栏目: 智能运维

Ubuntu / Linux 下,opendir() 本身不能递归遍历目录

原因

opendir() 只能:

  • 打开一个目录
  • 配合 readdir() 读取该目录下的直接子项(文件或子目录)

不会自动进入子目录,因此需要你在代码中手动递归


典型递归遍历方式(C 语言示例)

#include <stdio.h>
#include <dirent.h>
#include <sys/stat.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 fullpath[1024];
        snprintf(fullpath, sizeof(fullpath), "%s/%s", path, entry->d_name);

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

        if (S_ISDIR(st.st_mode)) {
            printf("DIR: %s\n", fullpath);
            list_dir(fullpath);  // 递归
        } else {
            printf("FILE: %s\n", fullpath);
        }
    }
    closedir(dir);
}

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

如果你不想自己写递归

可以用:

  • ftw() / nftw()(标准库,已不推荐)
  • find 命令
  • glob()(仅一层)

例如:

find /path -type f

总结

opendir() 只能打开单层目录
不支持递归
✅ 递归必须 手动实现

如果你是用 C / C++ / Python / Shell,我可以给你对应语言的递归示例。

0