如何用copendir实现目录递归遍历

436
2025/3/23 9:33:04
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

opendir 函数用于打开一个目录流,而 readdir 函数用于读取目录中的条目。要实现目录的递归遍历,你需要结合这两个函数,并对子目录进行递归调用。

以下是一个使用 opendirreaddir 实现目录递归遍历的示例代码(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 = 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 <directory_path>\n", argv[0]);
        return EXIT_FAILURE;
    }

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

这个程序接受一个命令行参数作为要遍历的目录路径。list_directory_contents 函数会打开目录,读取其中的条目,并检查每个条目是文件还是子目录。如果是子目录,它会递归调用自身以继续遍历子目录的内容。

编译并运行这个程序,传入一个目录路径作为参数,它将打印出该目录及其所有子目录中的文件和目录。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: linux怎么搜索文件里的字符串