温馨提示×

debian copendir能不能递归遍历

小樊
45
2026-09-25 06:33:44
栏目: 智能运维

在 Debian(以及一般 Linux/Unix 系统) 里,你提到的 copendir 应该是指 opendir / readdir 这套目录遍历 API(POSIX 标准,C 语言)。

先给结论:

opendir + readdir 本身不能递归遍历目录,只能遍历“当前一层目录”。
要递归遍历,必须自己在代码里写递归逻辑。


1. opendir / readdir 的能力边界

DIR *dir = opendir(path);
struct dirent *entry;

while ((entry = readdir(dir)) != NULL) {
    // 只能看到当前目录下的文件和子目录名
}
closedir(dir);
  • ✅ 能列出:
    • 普通文件
    • 子目录
  • ❌ 不会自动进入子目录
  • ❌ 不会递归

2. 如何递归遍历(标准做法)

思路

  1. opendir 打开目录
  2. readdir 读取每一项
  3. 如果是目录(且不是 . / ..):
    • 拼路径
    • 递归调用自己

示例(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 fullpath[1024];
        snprintf(fullpath, sizeof(fullpath), "%s/%s", path, entry->d_name);

        struct stat st;
        stat(fullpath, &st);

        if (S_ISDIR(st.st_mode)) {
            printf("DIR: %s\n", fullpath);
            list_dir(fullpath);  // 递归
        } else {
            printf("FILE: %s\n", fullpath);
        }
    }
    closedir(dir);
}

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

3. Debian 下“更省事”的方式

如果你不想自己写递归:

✅ ftw / nftw(标准库,已支持递归)

#include <ftw.h>

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

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

✅ 命令行(非 C)

find /path -type f

4. 总结

方式 是否递归 说明
opendir + readdir ❌ 手动递归
自己写递归 ✅ 最常见
nftw ✅ 推荐
find ✅ 非编程场景

如果你是:

  • 写 C 程序
  • 写 shell
  • 想避免符号链接死循环**

可以告诉我,我可以给你更针对性的示例。

0 踩