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

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

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

#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

你也可能喜欢

发表评论