温馨提示×

debian copendir能否递归读取

小樊
43
2026-09-01 01:16:04
栏目: 智能运维

在 Debian(以及一般 Linux/POSIX 系统)里,opendir() 本身不能递归读取目录

说明

  • opendir() / readdir() 只能打开并遍历一个目录下的直接条目
  • 它不会自动进入子目录
  • 是否递归,需要你自己写代码实现

典型递归读取方式

一般做法是用 opendir + readdir + stat,遇到目录就递归:

#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("DIR: %s\n", full);
            list_dir(full);   // 递归
        } else {
            printf("FILE: %s\n", full);
        }
    }
    closedir(dir);
}

如果你不想自己写

  • Shellfind /path
  • C 高级封装nftw()(标准库,支持递归)
  • C++std::filesystem::recursive_directory_iterator(C++17)

总结

opendir 只能读一层目录,递归必须自己实现或用其他接口

如果你需要 C / C++ / Shell / Python 的具体递归示例,我可以按你用的语言给。

0