温馨提示×

如何用copendir实现递归遍历

小樊
33
2025-12-19 03:40:30
栏目: 编程语言

opendir 函数用于打开一个目录流,以便读取目录中的条目。然而,opendir 本身并不支持递归遍历目录。要实现递归遍历,你需要结合使用 opendirreaddirclosedir 函数,并在遇到子目录时递归调用遍历函数。

以下是一个使用 C 语言实现的递归遍历目录的示例代码:

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

void list_directory_contents(const char *path) {
    DIR *dir;
    struct dirent *entry;
    struct stat path_stat;

    dir = opendir(path);
    if (dir == NULL) {
        perror("opendir");
        return;
    }

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

        // 获取文件/目录的详细信息
        if (stat(full_path, &path_stat) == -1) {
            perror("stat");
            continue;
        }

        // 如果是目录,递归调用
        if (S_ISDIR(path_stat.st_mode)) {
            list_directory_contents(full_path);
        } else {
            // 如果是文件,打印文件名
            printf("%s\n", full_path);
        }
    }

    closedir(dir);
}

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

    list_directory_contents(argv[1]);
    return EXIT_SUCCESS;
}

代码说明:

  1. list_directory_contents 函数

    • 打开指定路径的目录。
    • 使用 readdir 读取目录中的每个条目。
    • 跳过 ... 条目。
    • 构建每个条目的完整路径。
    • 使用 stat 获取文件/目录的详细信息。
    • 如果是目录,递归调用 list_directory_contents
    • 如果是文件,打印文件名。
    • 关闭目录流。
  2. main 函数

    • 检查命令行参数,确保提供了一个目录路径。
    • 调用 list_directory_contents 函数开始递归遍历。

编译和运行:

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

这个程序会递归地遍历指定目录及其所有子目录,并打印出所有文件的路径。

0