温馨提示×

debian copendir可否递归读取

小樊
41
2026-09-09 23:44:03
栏目: 智能运维

在 Debian(以及一般的 Linux/Unix 系统)里,opendir 本身不能递归读取目录,它只能打开一个目录,然后配合 readdir 读取该目录下的直接条目(文件和子目录)。

为什么不能递归

  • opendir(const char *name)
    → 只打开一个目录流
  • readdir(DIR *)
    → 每次返回一个目录项(不含子目录里的内容)
  • 是否进入子目录,需要你自己判断并再次调用 opendir

递归读取的正确做法

你需要在代码中手动递归:

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

补充

  • opendir + readdir ≠ find
  • 如果你只是用命令,Debian 上可以直接:
    find /path -type f
    
  • 如果你想要库级递归,可以用:
    • nftw()(POSIX,推荐)
    • fts_open()(BSD 风格)

总结

✅ opendir 只能读一层
❌ 不能自动递归
✅ 递归必须自己写或用 nftw / find

如果你想要 C 语言递归示例 或 用 nftw 的实现,我可以给你现成代码。

0 踩