温馨提示×

ubuntu readdir如何递归子目录

小樊
36
2026-09-18 18:30:54
栏目: 智能运维

在 Ubuntu(Linux)下,如果你想递归遍历目录(包括子目录),常见做法有几种,取决于你用的是 Shell 命令 还是 C 语言 readdir()。


一、Shell 命令方式(最简单)

1. 使用 find

find /path/to/dir -type f

递归列出所有文件。

find /path/to/dir -type d

递归列出所有目录。

2. 使用 ls -R

ls -R /path/to/dir

二、C 语言 readdir 递归子目录(重点)

readdir() 本身不会递归,需要你自己写递归函数。

基本思路

  1. opendir() 打开目录
  2. readdir() 读取每一项
  3. 如果是目录(且不是 . 和 ..)
  4. 递归调用自己

示例:C 语言递归遍历目录

#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);

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

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

int main() {
    list_dir(".");
    return 0;
}

编译运行

gcc readdir_recursive.c -o readdir_recursive
./readdir_recursive

三、常见问题

1. readdir 为什么不能自动递归?

  • readdir() 只读取当前目录项
  • 是否进入子目录由程序员决定

2. 如何避免符号链接死循环?

lstat(fullpath, &st);
if (S_ISLNK(st.st_mode)) continue;

四、推荐方案总结

场景 推荐
命令行 find
C 程序 opendir + readdir + 递归
高性能 nftw()

如果你需要 C++ / nftw / 过滤特定文件类型 的示例,也可以告诉我。

0 踩