登录
首页 >  文章 >  linux

手把手教你用readdir实现文件夹递归遍历(附代码)

时间:2025-06-20 19:57:09 246浏览 收藏

想知道如何用 `readdir` 函数实现递归遍历文件夹吗?本文将手把手教你利用 `readdir` 函数结合 `opendir`、`closedir` 和 `stat` 函数,用C语言实现一个完整的递归遍历目录的程序。通过本文,你将学会如何读取目录下的文件和子目录,并深入子目录进行递归操作,最终打印出所有文件和目录的路径。 无论你是C语言初学者还是有一定经验的开发者,都能从本文中获益,掌握 `readdir` 函数在文件系统操作中的应用技巧。立即阅读,提升你的文件操作技能!

readdir如何实现递归遍历

readdir 函数本身并不提供递归遍历目录的功能,它只是用于读取指定目录下的文件和子目录。要实现递归遍历,你需要结合 readdir 和其他函数(如 opendir、closedir 和 stat)来完成。以下是一个使用 C 语言实现的递归遍历目录的示例:

#include 
#include 
#include 
#include 
#include 

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

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

    while ((entry = readdir(dir)) != NULL) {
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
            continue;
        }

        snprintf(path_stat.path, sizeof(path_stat.path), "%s/%s", path, entry->d_name);
        if (stat(path_stat.path, &path_stat) == -1) {
            perror("stat");
            continue;
        }

        if (S_ISDIR(path_stat.st_mode)) {
            printf("Directory: %s\n", path_stat.path);
            list_directory_contents(path_stat.path);
        } else {
            printf("File: %s\n", path_stat.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;
}

这个程序接受一个目录路径作为命令行参数,然后递归地遍历该目录及其所有子目录,打印出所有文件和目录的路径。注意,这个程序没有处理符号链接和权限问题,实际使用时可能需要根据需求进行相应的修改。

今天关于《手把手教你用readdir实现文件夹递归遍历(附代码)》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>