登录
首页 >  文章 >  linux

Linux readdir递归遍历?看这篇就够了!

时间:2025-06-06 13:00:32 428浏览 收藏

你在学习文章相关的知识吗?本文《Linux readdir递归遍历?看这篇就够了! 》,主要介绍的内容就涉及到,如果你想提升自己的开发能力,就不要错过这篇文章,大家要知道编程理论基础和实战操作都是不可或缺的哦!

在Linux系统中,利用readdir函数可以实现目录的递归遍历。下面是一个示例代码,展示了如何通过readdir和opendir等函数来递归遍历目录及其子目录:

#include 
#include 
#include 
#include 
#include 

void traverse_directory(const char *path) {
    DIR *dir;
    struct dirent *entry;
    struct stat path_stat;
    char path_stat_path[1024];

    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);
            traverse_directory(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;
    }

    traverse_directory(argv[1]);

    return EXIT_SUCCESS;
}

代码解析

  1. 头文件包含

    • stdio.h:用于标准输入输出操作。
    • stdlib.h:用于标准库函数。
    • dirent.h:用于目录操作。
    • string.h:用于字符串操作。
    • sys/stat.h:用于获取文件状态信息。
  2. traverse_directory函数

    • 接受一个目录路径作为参数。
    • 使用opendir打开目录。
    • 使用readdir读取目录中的条目。
    • 对每个条目,使用stat获取文件状态信息。
    • 如果条目是目录,则递归调用traverse_directory
    • 如果条目是文件,则打印文件路径。
    • 最后关闭目录。
  3. main函数

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

编译与执行

使用以下命令编译程序:

gcc -o listdir listdir.c

然后运行程序并指定要遍历的目录:

./listdir /path/to/directory

该程序将递归地遍历指定的目录及其所有子目录,并打印每个文件和目录的路径。

Linux readdir如何实现递归遍历

今天关于《Linux readdir递归遍历?看这篇就够了! 》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

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