温馨提示×

centos readdir能否递归

小樊
38
2026-09-27 08:00:02
栏目: 智能运维

简短回答:readdir 本身不能递归,它只能读取单个目录下的条目;递归需要你在代码里自己实现。


详细说明

1. readdir 是什么

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

  • opendir():打开一个目录
  • readdir():读取目录中的一个条目(文件或子目录)
  • closedir():关闭目录

readdir 不会进入子目录,它只返回当前目录下的内容。


2. 如何实现递归读取目录(C 示例)

你需要:

  • 用 readdir 遍历目录
  • 遇到目录时,递归调用自己
  • 用 stat 判断是否是目录
#include <stdio.h>
#include <dirent.h>
#include <sys/stat.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 fullpath[1024];
        snprintf(fullpath, sizeof(fullpath), "%s/%s", path, entry->d_name);

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

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

3. 如果不想自己写递归

✅ 使用 ftw / nftw(系统提供)

#include <ftw.h>

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

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

✅ Shell 中

find /path -type f

4. 总结

方式 是否递归 说明
readdir ❌ 否 只能读一层
readdir + 自己写递归 ✅ 是 常见做法
nftw ✅ 是 系统封装
find ✅ 是 命令行

如果你是用 C / C++ / Python / Shell 写,我可以给你对应版本的递归示例。

0 踩