温馨提示×

centos readdir能否递归遍历

小樊
49
2026-09-06 07:17:38
栏目: 智能运维

简短结论:readdir 本身不能递归遍历,它只能读取某一个目录下的直接条目;递归遍历需要你在代码里自己写递归逻辑


1. readdir 是什么

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

struct dirent *readdir(DIR *dirp);

作用:

  • 打开一个目录(opendir
  • 一次读取当前目录中的一个条目
  • 不进入子目录
  • 不递归

2. 为什么不能递归

readdir 只做一件事:

读取“当前目录”里的文件名(文件 / 子目录 / 符号链接等)

它:

  • ❌ 不会自动进入子目录
  • ❌ 不会遍历整棵树
  • ✅ 需要你判断 d_type == DT_DIR 后手动递归

3. 递归遍历的正确做法(C 示例)

#include <stdio.h>
#include <dirent.h>
#include <string.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);

        if (entry->d_type == DT_DIR) {
            list_dir(full);  // 递归
        }
    }
    closedir(dir);
}

✅ 这里递归是你写的,不是 readdir 提供的


4. 常见替代方案(更省事)

✅ 命令行

find /path -type f

✅ 高级语言

  • Python:os.walk()
  • Go:filepath.Walk()
  • Shell:ls -R

5. 总结

问题 答案
readdir 能递归吗 ❌ 不能
能遍历子目录吗 ❌ 不能
怎么实现递归 ✅ 自己递归调用
推荐方式 find 或高级语言

如果你需要 CentOS 下 C / C++ / Shell 的完整递归示例,可以告诉我具体语言。

0