C++递归式遍历文件夹及文件

void GetAllTypeFileX86(std::map<std::string, std::string>& files,
	const std::string& path, const std::string& fileType)
{
	int32_t hFile = 0;            //文件句柄
	struct _finddata_t fileinfo;  //文件信息读取结构
	std::string p;

	if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1)
	{
		do
		{
			if ((fileinfo.attrib & _A_SUBDIR))    //比较文件类型是否是文件夹
			{
				if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
				{
					GetAllTypeFileX86(files, p.assign(path).append("\\").append(fileinfo.name), fileType); //如果是文件夹,继续向下遍历
				}
			}
			else    //是文件
			{
				std::string fileName = fileinfo.name;
				int32_t pos = fileName.rfind('_');  //此处为我的文件判断规则,可自定义。
				if (pos == std::string::npos || fileType != fileName.substr(pos))continue;

				files.insert(std::pair<std::string, std::string>(fileinfo.name, path));  //是文件,将其路径加入到files集合中
			}
		} while (_findnext(hFile, &fileinfo) == 0);  //寻找下一个,成功返回0,否则-1
		_findclose(hFile);
	}
}

使用lambda表达式一次性遍历多类型文件。

void GetAllTypeFileX86(const std::string& path,std::function<void(std::string, std::string)> fileTypeCheck);
int main
{
	//进行新dmp文件的获取
		std::map<std::string, std::string>Files1;
		std::map<std::string, std::string>Files2;

		//类型判断函数
		std::function<void(std::string, std::string)> fun = [&Files1, &Files2]
		(IN const std::string& name, IN const std::string& path)
		{
			int32_t pos = name.rfind('.');
			if (pos == std::string::npos)return;
			std::string type = name.substr(pos);
			std::transform(type.begin(), type.end(), type.begin(), toupper); //将文件名变为大写
			if (type == "type1")Files1.insert({ name, path });
			else if (type == "type2")Files2.insert({ name, path });
		};
		GetAllFullTypeFileX86(std::string(pathBuffer) + TEMP, fun);
}

void GetAllTypeFileX86(const std::string& path,std::function<void(std::string, std::string)> fileTypeCheck)
{
	int32_t hFile = 0;            //文件句柄
	struct _finddata_t fileinfo;  //文件信息读取结构
	std::string p;

	if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1)
	{
		do
		{
			if ((fileinfo.attrib & _A_SUBDIR))    //比较文件类型是否是文件夹
			{
				if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
				{
					GetAllTypeFileX86(files, p.assign(path).append("\\").append(fileinfo.name), fileTypeCheck); //如果是文件夹,继续向下遍历
				}
			}
			else    //是文件
			{
				fileTypeCheck(fileinfo.name, path);
			}
		} while (_findnext(hFile, &fileinfo) == 0);  //寻找下一个,成功返回0,否则-1
		_findclose(hFile);
	}
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值