首页主机资讯readdir如何遍历子目录

readdir如何遍历子目录

时间2025-12-23 09:53:05发布访客分类主机资讯浏览1462
导读:readdir 是一个用于读取目录内容的函数,通常在 C 语言中使用。要使用 readdir 遍历子目录,你需要递归地处理每个目录。以下是一个简单的示例,展示了如何使用 readdir 和 opendir 函数遍历子目录: #include...

readdir 是一个用于读取目录内容的函数,通常在 C 语言中使用。要使用 readdir 遍历子目录,你需要递归地处理每个目录。以下是一个简单的示例,展示了如何使用 readdiropendir 函数遍历子目录:

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

        }
    

        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 <
    directory>
    \n", argv[0]);
    
        return EXIT_FAILURE;

    }
    

    list_directory_contents(argv[1]);
    

    return EXIT_SUCCESS;

}
    

这个程序接受一个目录作为命令行参数,并递归地列出该目录及其所有子目录中的文件和目录。注意,这个示例没有处理符号链接和其他可能的错误情况。在实际应用中,你可能需要根据你的需求进行相应的调整。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: readdir如何遍历子目录
本文地址: https://pptw.com/jishu/778201.html
ubuntu中copendir命令最新版本 ubuntu中如何调试copendir命令

游客 回复需填写必要信息