温馨提示×

debian copendir能否递归遍历

小樊
35
2026-09-22 05:40:21
栏目: 智能运维

Debian(以及一般的 Linux/glibc) 中,opendir() 本身不能递归遍历目录,它只能打开并读取单个目录的内容。

1. opendir / readdir 的能力

  • opendir():打开一个目录
  • readdir():读取该目录下的直接子项(文件或子目录)
  • 不会自动进入子目录

示例(非递归):

DIR *dir = opendir("/path");
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
    printf("%s\n", entry->d_name);
}
closedir(dir);

2. 如何实现“递归遍历”

需要自己写递归逻辑

#include <dirent.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>

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

3. 更简单的替代方案(Debian)

如果不坚持用 opendir,可以用:

  • ftw() / nftw()(标准库,支持递归)
  • find 命令
  • glob()(有限递归)

结论

opendir 可以用于递归遍历的基础
❌ 但 不能自动递归,必须自己实现递归逻辑

如果你需要 C 示例 / nftw 示例 / 性能注意点,可以继续问我。

0