温馨提示×

debian readdir能否递归

小樊
44
2026-09-04 11:53:31
栏目: 智能运维

Debian(以及一般 Linux/Unix) 里,readdir 本身不能递归

1. readdir 是什么

readdir 是 POSIX 标准中的函数(在 <dirent.h> 中定义),作用是:

读取一个已打开目录流中的下一个目录项(entry)

原型:

struct dirent *readdir(DIR *dirp);

它只做一件事:遍历当前目录下的直接子项(文件或子目录),不会自动进入子目录。


2. 为什么不能递归

  • readdir 只返回一个 dirent
  • 它不包含子目录内容
  • 是否进入子目录,由程序员决定

所以:

readdir = 单层遍历
readdir ≠ 递归遍历


3. 如何实现递归遍历(Debian / Linux)

需要你自己在代码里递归调用:

C 示例(简化)

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

void list_dir(const char *path) {
    DIR *dir = opendir(path);
    struct dirent *entry;
    char full[1024];

    while ((entry = readdir(dir)) != NULL) {
        if (strcmp(entry->d_name, ".") == 0 ||
            strcmp(entry->d_name, "..") == 0)
            continue;

        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);
}

4. 更简单的方式(不写 C)

如果你只是想在 Debian 上递归列出目录:

shell

find /path
# 或
ls -R /path

高级 C 替代(GNU)

  • nftw()(递归遍历文件系统)
  • fts_open()(更现代)

总结

问题 答案
readdir 能递归吗 ❌ 不能
需要自己递归吗 ✅ 需要
Debian 特有吗 ❌ 不是,POSIX 标准

如果你是想用 C / Python / shell / 某个具体场景,我可以给你更针对性的例子。

0