温馨提示×

ubuntu copendir能否递归子目录

小樊
34
2026-09-23 22:43:04
栏目: 智能运维

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

说明

  • opendir():只打开一个目录,返回一个 DIR *
  • readdir():读取该目录下的直接条目(文件和子目录)
  • 不会自动进入子目录

是否递归,完全由你在代码里自己实现。

典型做法(C 语言)

#include <dirent.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.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);
}

如果你想“递归”

✅ 用 opendir + readdir + 递归调用
❌ opendir 本身做不到

替代方案

  • nftw()(更专业,支持递归遍历)
  • find 命令(Shell 层)
  • glob()(有限递归)

如果你说的是 某个具体语言或库(如 Python、Go、C++ filesystem),可以告诉我,我可以给对应示例。

0 踩