温馨提示×

centos readdir怎么递归

小樊
49
2026-09-12 01:47:15
栏目: 智能运维

在 CentOS(Linux) 里,readdir 本身是 不递归的,它只读取当前目录下的条目。要实现“递归读取目录”,通常是:

readdir + 递归调用

下面给你几种常见做法(C 语言 / shell / find)。


一、C 语言:readdir 递归实现(最标准)

基本思路

  1. opendir() 打开目录
  2. readdir() 读取每一项
  3. 如果是目录(DT_DIR),并且不是 . 和 ..,就递归调用

示例代码(CentOS 可用)

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

        if (entry->d_type == DT_DIR) {
            printf("DIR: %s\n", fullpath);
            list_dir(fullpath);  // 递归
        } else {
            printf("FILE: %s\n", fullpath);
        }
    }
    closedir(dir);
}

int main(int argc, char *argv[]) {
    if (argc < 2) {
        printf("Usage: %s <dir>\n", argv[0]);
        return 1;
    }
    list_dir(argv[1]);
    return 0;
}

编译

gcc readdir_recursive.c -o readdir_recursive

运行

./readdir_recursive /path/to/dir

二、Shell 方式(CentOS 常用)

如果你只是想在 CentOS 上递归列目录,不用写 C:

find /path/to/dir

或只列目录:

find /path/to/dir -type d

三、使用 nftw(更专业,C 语言)

如果你不想自己写递归,可以用标准库:

#include <ftw.h>
#include <stdio.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/to/dir", cb, 20, 0);
    return 0;
}

四、常见问题

1. readdir 为什么不能递归?

  • readdir 只读取一个目录
  • Linux 目录结构是树形,必须手动递归

2. 符号链接怎么办?

  • DT_LNK 需要处理,否则可能死循环
  • 建议用 stat() 判断真实类型

如果你说的是:

  • Python 的 readdir
  • 某个具体程序/库
  • CentOS 版本(7 / 8 / Stream)

告诉我,我可以给你更针对性的示例。

0 踩