温馨提示×

debian readdir能否递归遍历

小樊
43
2026-09-16 12:40:03
栏目: 智能运维

在 Debian(Linux) 下,readdir 本身不能递归遍历目录,它只能读取当前目录中的一个条目(一次调用返回一个文件/子目录)。

1. readdir 是什么

  • readdir 是 POSIX / glibc 提供的函数
  • 配合 opendir / readdir / closedir 使用
  • 作用:读取一个已打开目录中的下一个条目
  • 不会自动进入子目录

示例(只能列出当前目录):

DIR *dir = opendir(".");
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 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);
        printf("%s\n", full);

        struct stat st;
        if (stat(full, &st) == 0 && S_ISDIR(st.st_mode)) {
            list_dir(full);  // 递归
        }
    }
    closedir(dir);
}

3. 更推荐的方式(Debian 下)

如果你不想自己写递归:

✅ ftw / nftw(标准库)

#include <ftw.h>

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

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

✅ find 命令(最简单)

find /path -type f

总结

方式 是否递归 说明
readdir ❌ 仅单层
readdir + 递归代码 ✅ 常见做法
nftw ✅ 推荐
find ✅ 命令行

如果你是在 C / C++ / Shell / Python 里用,我可以给你对应示例。

0 踩