前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Linux C++ 遍历文件夹

Linux C++ 遍历文件夹

作者头像
灯珑LoGin
发布2022-10-31 13:36:06
6.6K0
发布2022-10-31 13:36:06
举报
文章被收录于专栏:龙进的专栏

(本文仅适用于Linux C++)

这个方法用到了dirent.h,相关资料:

C++ struct dirent 和 DIR

具体代码实现,遍历了给定目录下的所有文件夹和文件:

代码语言:javascript
复制
#include<bits/stdc++.h>

#ifdef linux
#include<dirent.h>
#endif

using namespace std;

struct walk_return
{
    vector<string> files;
    vector<string>dirs;
};


walk_return walk_folder(string base_dir)
{
    vector<string>files;
    vector<string>dirs;

    #ifdef linux
    //在linux下walk_folder
    DIR *dir;

    struct dirent *ptr;

    //打开文件夹失败
    if((dir=opendir(base_dir.c_str()))==NULL)
    {
        cerr<<"[ERROR]打开文件夹失败"<<endl;
        exit(1);
    }

    while((ptr=readdir(dir))!=NULL)
    {
        //是当前路径或者父目录
        if(strcmp(ptr->d_name, ".")==0||strcmp(ptr->d_name, "..") == 0)
            continue;
        else if (ptr->d_type == 8)//file
            files.push_back(ptr->d_name);
        else if (ptr->d_type == 10)//link file
            continue;
        else if (ptr->d_type == 4)//dir
        {
            dirs.push_back(ptr->d_name);
        }
    }

    closedir(dir);


    #endif

    walk_return wk;
    wk.dirs = dirs;
    wk.files = files;
    return wk;
}


int main()
{
    auto ans = walk_folder(".");
    cout<<"files:"<<endl;
    for(auto x : ans.files)
        cout<<x<<endl;

    cout<<"dirs"<<endl;
    for(auto x: ans.dirs)
        cout<<x<<endl;

}

转载请注明来源:https://www.longjin666.top/?p=978

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021年6月1日20,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档