信息发布→ 登录 注册 退出

Linux readdir怎样支持递归遍历

发布时间:2025-06-04

点击量:

在Linux系统里,readdir函数并未内置递归遍历目录的功能。它的主要作用是获取指定目录内的文件及子目录信息。若要完成递归遍历,则需自行构建递归函数来达成目标。

以下为一段采用C语言编写的递归遍历目录结构的代码示例:

#include 
#include 
#include 
#include 
#include 

void traverse_directory(const char *path) {
    DIR *dp;
    struct dirent *entry;
    struct stat file_stat;

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

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

        char full_path[1024];
        snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);
        if (lstat(full_path, &file_stat) == -1) {
            perror("lstat");
            continue;
        }

        if (S_ISDIR(file_stat.st_mode)) {
            printf("Directory: %s\n", full_path);
            traverse_directory(full_path);
        } else {
            printf("File: %s\n", full_path);
        }
    }

    closedir(dp);
}

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

此程序接收一个目录路径作为输入参数,并以递归方式展示该目录下所有的文件与子目录。需要注意的是,本示例未涉及符号链接等特殊情况的处理,实际应用时应依据具体要求作出调整。

标签:# linux  # c语言  # ai  # 递归  # 遍历  # 的是  # 并以  # 具体要求  # 时应  # 若要  # 需要注意  # 实际应用  # 与子  
在线客服
服务热线

服务热线

4008888355

微信咨询
二维码
返回顶部
×二维码

截屏,微信识别二维码

打开微信

微信号已复制,请打开微信添加咨询详情!