温馨提示×

debian copendir能递归读取吗

小樊
43
2026-10-27 11:58:24
栏目: 智能运维

在 Debian(以及所有类 Unix 系统)里,opendir() 本身不能递归读取目录。

结论先说

  • opendir():只打开一个目录
  • readdir():只读取该目录下的条目(不进入子目录)
  • 递归是你要自己写的逻辑

标准做法(POSIX / Linux)

典型递归读取目录的方式是:

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

更简单的方法(推荐)

1️⃣ nftw()(标准库,递归遍历)

#include <ftw.h>
#include <stdio.h>

int cb(const char *path, const struct stat *st, int type, struct FTW *ftw) {
    printf("%s\n", path);
    return 0;
}

int main() {
    nftw(".", cb, 20, FTW_PHYS);
}

2️⃣ find 命令(非 C 程序)

find /path -type f

总结

函数 是否递归
opendir ❌ 否
readdir ❌ 否
nftw ✅ 是
find ✅ 是

如果你是 写 C 程序 / shell 脚本 / 内核模块,可以告诉我具体使用场景,我可以给你更合适的方案。

0 踩