C++ Primer:查找指定文件夹下指定类型的文件

1、背景

  给定一个路径和一种文件类型,查找在该路径下所有该类型的文件。

文件夹所在路径

2、实现

#include <iostream>
#include <io.h>
#include <string>
#include <set>
using namespace std;

// 查找路径path下,文件类型为type的所有文件
void find_files(const string &path, const string &type, set<string> &files)
{
    _finddata_t data;
    auto handle = _findfirst((path + "/*.*").c_str(), &data); //读取第1文件或文件夹
    if (handle == -1)                                         //判断是否可以读取文件
    {
        cout << "can not read file!";
        return;
    }
    do
    {
        string s = data.name;        //文件名
        if (data.attrib & _A_SUBDIR) // 目录
        {
            // if (s != "." && s != "..") //排除文件夹.和文件夹..
            //     cout << "dir: " << s << endl;
        }
        else // 文件
        {
            string s1 = "." + type;
            if (s.rfind(s1) == s.size() - s1.size()) // 判断后缀是否为.type
            {
                files.insert(path + "/" + s);
                // cout << "file: " << s << endl;
            }
        }
    } while (_findnext(handle, &data) == 0); //读取下一个文件或文件夹
    _findclose(handle);                      // 关闭搜索句柄
}

int main()
{
    string path = "E:/VSCode/git/my_learning_opencv3/test"; // 路径名
    string type = "jpg";                                    //文件类型
    set<string> files;                                      //存放找到的文件
    find_files(path, type, files);
    for (auto file : files) //浏览找到的文件
        cout << file << endl;
    return 0;
}

运行结果:
运行结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值