C++ 获取指定文件夹下指定后缀名文件

#include <dirent.h>
#include <iostream>
#include <regex>
#include <string>
std::vector<std::string> faceDescriptorManager::get_all_files(std::string path, std::string suffix)
{
    std::vector<std::string> files;
    files.clear();
    DIR *dp;
    struct dirent *dirp;
    if((dp = opendir(path.c_str())) == NULL)
    {
        cout << "Can not open " << path << endl;
        return files;
    }
    regex reg_obj(suffix, regex::icase);
    while((dirp = readdir(dp)) != NULL)
    {
        if(dirp -> d_type == 8)  // 4 means catalog; 8 means file; 0 means unknown
        {
            if(regex_match(dirp->d_name, reg_obj))
            {
//                cout << dirp->d_name << endl;
                string all_path = path + dirp->d_name;
                files.push_back(all_path);
                cout << dirp->d_name << " " << dirp->d_ino << " " << dirp->d_off << " " << dirp->d_reclen << " " << dirp->d_type << endl;
            }
        }
    }
    closedir(dp);
    return files;
}
  • 上一个方法只能获取文件夹下的文件,如果需要获得所有子文件夹里的所有特定后缀名的文件,可用以下方法
#include <regex>
#include <string>
#include <vector>
#include <dirent.h>
#include <iostream>

using namespace std;

std::vector<std::string> get_all_files(std::string path, std::string suffix)
{
    std::vector<std::string> files;
//    files.clear();
    regex reg_obj(suffix, regex::icase);

    std::vector<std::string> paths;
    paths.push_back(path);

    for(int i = 0; i < paths.size(); i++)
    {
        string curr_path = paths[i];
        DIR *dp;
        struct dirent *dirp;
        if((dp = opendir(curr_path.c_str())) == NULL)
        {
            cerr << "can not open this file." << endl;
            continue;
        }
        while((dirp = readdir(dp)) != NULL)
        {
            if(dirp->d_type == 4)
            {
                if((dirp->d_name)[0] == '.') // 这里很奇怪,每个文件夹下都会有两个文件: '.'  和   '..'
                    continue;
//                cout << dirp->d_name << " ";
                string tmp_path = curr_path + "/" + dirp->d_name;
//                cout << tmp_path << " ";
                paths.push_back(tmp_path);
//                cout << paths[paths.size() - 1] << endl;
            }
            else if(dirp->d_type == 8)
            {
                if(regex_match(dirp->d_name, reg_obj))
                {
                    string full_path = curr_path + "/" + dirp->d_name;
                    files.push_back(full_path);
                }
            }
        }
        closedir(dp);
    }
    return files;
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值