温馨提示×

ubuntu copendir怎样递归子目录

小樊
46
2026-09-08 15:31:30
栏目: 智能运维

在 Ubuntu(Linux)下,如果你想递归遍历子目录,通常不是用 opendir 一个函数完成的,而是 opendir + readdir + 递归调用 来实现。

下面给你一个完整、可运行的 C 语言示例,演示如何用 opendir / readdir 递归遍历目录。


核心思路

  1. opendir() 打开目录
  2. readdir() 读取目录项
  3. 如果是目录(且不是 ...),递归调用自己
  4. 如果是文件,直接处理

示例:递归列出所有文件和目录

#include <stdio.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <unistd.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 full_path[1024];
        snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);

        // 获取文件信息
        struct stat st;
        if (stat(full_path, &st) == -1) {
            perror("stat");
            continue;
        }

        if (S_ISDIR(st.st_mode)) {
            printf("目录: %s\n", full_path);
            list_dir(full_path);   // 递归子目录
        } else {
            printf("文件: %s\n", full_path);
        }
    }

    closedir(dir);
}

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

编译 & 运行

gcc recursive_ls.c -o recursive_ls
./recursive_ls /path/to/dir

关键点说明

  • opendir 只能打开一层目录
  • 递归靠你自己写
  • entry->d_type 也可判断类型(但不是所有文件系统都支持)
  • 更现代的方式:nftw()(不推荐初学时用)

如果你只是想用命令(非 C)

find /path/to/dir

如果你是 C / C++ / shell / Python 哪种方式想递归目录,我可以按你的需求再细化。

0