商城首页欢迎来到中国正版软件门户

您的位置: 首页 > 文章列表 > 编程开发 > 使用copendir进行递归目录遍历

使用copendir进行递归目录遍历

  发布于2026-07-12 阅读(0)

扫一扫,手机访问

在C语言里,opendir这个函数的作用是打开一个目录流——说白了就是让你能“看”那个文件夹里面的东西。但它自己可不会递归往下翻,要想把子目录里的文件也统统找出来,还得手动搭配readdir,逐个判断每个条目是不是目录,如果是,就再调一遍遍历函数。

使用copendir进行递归目录遍历

下面这段代码,就是C语言里实现递归目录遍历的经典写法:

#include 
#include 
#include 
#include 
#include 

void list_directory_contents(const char *path) {
    DIR *dir = opendir(path);
    if (dir == NULL) {
        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[PATH_MAX];
        snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);

        struct stat path_stat;
        if (stat(full_path, &path_stat) == -1) {
            perror("stat");
            continue;
        }

        if (S_ISDIR(path_stat.st_mode)) {
            printf("Directory: %s\n", full_path);
            list_directory_contents(full_path); // 递归调用
        } else {
            printf("File: %s\n", full_path);
        }
    }

    closedir(dir);
}

int main(int argc, char *argv[]) {
    if (argc != 2) {
        fprintf(stderr, "Usage: %s \n", argv[0]);
        return EXIT_FAILURE;
    }
    list_directory_contents(argv[1]);
    return EXIT_SUCCESS;
}

说明:

  1. opendir:先打开目录流,拿到一个 DIR * 指针。如果返回 NULL,说明路径有问题,直接报错退出。
  2. readdir:用 readdir 一次次读下一个条目,直到读完。要注意跳过 ... 这两个特殊目录,否则会陷入无限循环。
  3. stat:拿到每个条目的详细信息,存在 struct stat 里。用 S_ISDIR 宏判断是不是目录。
  4. 递归:如果是目录,就把完整路径传给 list_directory_contents 继续往下走;如果是文件,直接打印名字。

编译和运行:

gcc -o listdir listdir.c
./listdir /path/to/directory

把上面代码保存成 listdir.c,用 gcc 编译,然后带上目标目录路径运行,就能看到它把所有子目录和文件的完整路径列出来了。整个过程很直接,但别忘了处理路径拼接和递归退出条件——不然很容易出 bug。

本文转载于:https://www.yisu.com/ask/34091430.html 如有侵犯,请联系zhengruancom@outlook.com删除。
免责声明:正软商城发布此文仅为传递信息,不代表正软商城认同其观点或证实其描述。

热门关注