温馨提示×

linux readdir可递归子目录吗

小樊
39
2026-09-23 23:08:06
栏目: 智能运维

简短结论:readdir 本身不能递归子目录,它只能读取一个目录下的条目(文件/子目录名),是否递归要由你在代码里自己实现。


1. readdir 是什么

readdir 是 POSIX 标准函数(<dirent.h>):

struct dirent *readdir(DIR *dirp);

作用:

  • 打开目录(opendir)
  • 逐个读取目录项
  • 不涉及子目录内容

它只知道:

  • 名字 d_name
  • 类型(部分系统有 d_type)

2. 为什么不能递归

readdir 不会:

  • 自动进入子目录
  • 自动遍历树结构

它只做一件事:读当前目录的下一个条目


3. 如何实现递归(自己写)

典型做法:

#include <dirent.h>
#include <string.h>
#include <sys/stat.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)) {
            printf("DIR: %s\n", full);
            list_dir(full);   // 递归
        } else {
            printf("FILE: %s\n", full);
        }
    }
    closedir(dir);
}

4. 更简单的方式(不自己写递归)

✅ ftw / nftw

#include <ftw.h>

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

nftw(".", cb, 20, FTW_DEPTH);

✅ find 命令

find . -type f

5. 总结

方式 是否递归
readdir ❌ 不递归
readdir + 自己写 ✅ 可递归
nftw ✅ 直接递归
find ✅ 最简单

如果你愿意,我可以:

  • 给你 C / C++ 完整示例
  • 讲 d_type 性能陷阱
  • 对比 readdir vs getdents

0 踩