温馨提示×

ubuntu copendir可否递归遍历

小樊
45
2026-10-11 12:36:59
栏目: 智能运维

在 Ubuntu / Linux 下,opendir() 本身不能递归遍历目录,它只能打开单个目录并配合 readdir() 读取该目录下的条目(文件和子目录)。

说明

  • opendir():打开一个目录
  • readdir():读取目录项
  • closedir():关闭目录

它们只处理一层目录,不会自动进入子目录。


如果要“递归遍历目录”

你需要 自己写递归逻辑(或在循环里处理子目录)。

示例(C 语言递归遍历)

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

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

常见替代方案

  • C++:std::filesystem::recursive_directory_iterator(C++17)
  • Shell:find /path -type f
  • Python:os.walk() / pathlib

如果你是用 C / C++ / 某种特定语言,可以告诉我,我可以给对应示例。

0 踩