温馨提示×

ubuntu readdir如何递归目录

小樊
39
2026-09-30 18:26:46
栏目: 智能运维

在 Ubuntu(Linux)下,readdir 本身只能读取一个目录的内容,不会自动递归。要实现“递归目录”,需要:

  1. 用 opendir + readdir 读取目录
  2. 判断 d_type 或 stat 是否是目录
  3. 如果是目录,递归调用自己

下面给你一个标准 C 语言示例(最贴近你问的 readdir)。


一、C 语言 readdir 递归示例

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>

void list_dir(const char *path) {
    DIR *dir = opendir(path);
    if (!dir) {
        perror("opendir");
        return;
    }

    struct dirent *entry;
    while ((entry = readdir(dir)) != NULL) {
        // 跳过 . 和 ..
        if (strcmp(entry->d_name, ".") == 0 ||
            strcmp(entry->d_name, "..") == 0)
            continue;

        // 拼接完整路径
        char fullpath[4096];
        snprintf(fullpath, sizeof(fullpath), "%s/%s", path, entry->d_name);

        // 判断是否是目录
        struct stat st;
        if (stat(fullpath, &st) == -1) {
            perror("stat");
            continue;
        }

        if (S_ISDIR(st.st_mode)) {
            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 recursive_readdir.c -o recursive_readdir
./recursive_readdir /path/to/dir

三、关键点说明

1. readdir 不会递归

  • readdir() 只返回一个目录项
  • 是否继续向下,由你决定

2. 为什么要用 stat

  • d_type 有时不可靠(某些文件系统)
  • stat() 更通用

3. 避免死循环

必须跳过:

.
..

四、如果你只是想“递归列目录”

Shell 更简单

find /path/to/dir
# 或
ls -R /path/to/dir

五、如果你用的是 C++

也可以用 <filesystem>(C++17):

#include <filesystem>
namespace fs = std::filesystem;

for (auto& p : fs::recursive_directory_iterator("/path")) {
    std::cout << p.path() << "\n";
}

如果你想要:

  • 只递归指定深度
  • 按文件类型过滤
  • 多线程递归
  • Python / Shell 版本

告诉我,我可以继续给你写。

0 踩