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;
}
运行结果: