【C++】寻找目录中的文件并提取关键字

14 篇文章 2 订阅

背景:

目前debug过程中需要导入很多素材,如果代码中直接写死比较麻烦且耗时,所以比较好的办法就是材料放在某目录中,由程序自动检索所有符合后缀的文件,然后进行操作。

 

void Find(const char* lpPath, std::vector<const std::string> &fileList)
{
	char szFind[MAX_PATH];
	WIN32_FIND_DATA FindFileData;
	
	strcpy(szFind, lpPath);

	strcat(szFind, "\\*.*");

	HANDLE hFind = ::FindFirstFile(szFind, &FindFileData);




	if (INVALID_HANDLE_VALUE == hFind){

		strcpy(szFind, lpPath);
		strcat(szFind, "\\*.*");
		hFind = ::FindFirstFile(szFind, &FindFileData);
		if (INVALID_HANDLE_VALUE == hFind)
			return;
	}

	while (true)
	{
		if (FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
		{
			if (FindFileData.cFileName[0] != '.')
			{
				char szFile[MAX_PATH];
				strcpy(szFile, lpPath);
				strcat(szFile, "\\");
				strcat(szFile, (char*)(FindFileData.cFileName));
				Find(szFile, fileList);
			}
		}
		else
		{
			std::string path = lpPath;
			path += "\\";
			path += FindFileData.cFileName;

			fileList.push_back(path);

		}
		//std::cout << FindFileData.cFileName<<::std::endl;
		if (!FindNextFile(hFind, &FindFileData))    break;
	}
	FindClose(hFind);
}


int main()
{
	std::cout << "put the input image path" << endl;
	std::string inputPath;
	std::getline(std::cin, inputPath);
	std::vector<const std::string> fileList;
	Find(inputPath.c_str(), fileList);

	std::vector<const std::string>::iterator it;
	for (it = fileList.begin(); it != fileList.end(); it++)
	{
		if (it->find("jpg") != -1 || it->find("png") != -1 || it->find("bmp") != -1 || it->find("JPEG") != -1 || it->find("JPG") != -1 ||
			it->find("PNG") != -1 || it->find("BMP") != -1 || it->find("jpeg") != -1)
			;//
		else
		{
			continue;
		}
		
		std::string imgPath = *it;
		//std::cout << imgPath << std::endl;

		int pos = it->find_last_of("\\");

		std::string imgname = it->substr(pos + 1);
		std::string imgdir = it->substr(0, pos);
		pos = imgname.find_last_of(".");

		imgname = imgname.substr(0, pos);

		printf( "[%s] [%s]\n", imgdir.c_str(), imgname.c_str());

		printf("\n");
	}

	return 0;
}

 

put the input image path
F:\videos
[F:\videos]\[1.jpg]

[F:\videos]\[2.jpg]

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值