温馨提示×

debian readdir能递归子目录吗

小樊
36
2026-10-21 21:34:23
栏目: 智能运维

在 Debian(以及所有 Linux/Unix 系统)里,readdir 本身不能递归子目录。

1. readdir 是什么

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

读取一个已经打开的目录流中的“下一个目录项”

它只能:

  • 读取当前目录下的文件和子目录名
  • 不包含递归能力
DIR *dir = opendir("/path");
struct dirent *entry;

while ((entry = readdir(dir)) != NULL) {
    // 只能拿到当前目录下的名字
}

2. 如何实现“递归读取子目录”

需要你自己写递归逻辑:

#include <dirent.h>
#include <sys/stat.h>
#include <string.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);
}

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

✅ 使用 nftw()(推荐)

#include <ftw.h>

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

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

✅ Shell 命令

find /path

总结

方式 是否递归
readdir ❌ 不递归
readdir + 递归代码 ✅
nftw ✅
find ✅

如果你是在 写 C 程序 / Python / Shell 或关心 性能/安全性(符号链接),可以告诉我,我可以给更合适的方案。

0 踩