温馨提示×

centos readdir能递归吗

小樊
39
2026-10-12 00:02:14
栏目: 智能运维

简短回答:readdir 本身不能递归,它只能读取一个目录下的条目,不能自动进入子目录。


详细说明

在 CentOS(以及所有 Linux / POSIX 系统)中:

  • readdir() 是 C 库函数(#include <dirent.h>)
  • 作用是:打开目录后,逐个读取当前目录中的文件/子目录名
  • 它 不会递归遍历子目录

示例(非递归)

DIR *dir = opendir("/path");
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
    printf("%s\n", entry->d_name);
}
closedir(dir);

上面代码 只会列出 /path 下的内容,不会进入子目录。


如果想递归目录,需要自己写逻辑

常见做法:

1. 自己递归(用 readdir + stat)

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

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

        snprintf(fullpath, sizeof(fullpath), "%s/%s", path, entry->d_name);

        struct stat st;
        stat(fullpath, &st);

        if (S_ISDIR(st.st_mode)) {
            list_dir(fullpath);  // 递归
        } else {
            printf("%s\n", fullpath);
        }
    }
    closedir(dir);
}

更简单的方式(推荐)

✅ ftw() / nftw()(标准库,支持递归)

#include <ftw.h>

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

nftw("/path", cb, 20, FTW_PHYS);

✅ Shell 命令(非编程)

find /path

总结

方式 是否递归
readdir ❌ 否
readdir + 自己写递归 ✅ 是
nftw ✅ 是
find ✅ 是

如果你是想 写 C 程序 / Shell 脚本 / 内核层面,可以告诉我具体场景,我可以给更合适的方案。

0 踩