windows系统C++搜索文件和文件夹

#include <iostream>
#include <vector>
using namespace std;

#include <afx.h>

#include <windows.h>


bool IsStringEndWithPostfix(wstring DirName, wstring PostFix)
{
	int str_len1 = DirName.size();
	int str_len2 = PostFix.size();

	int pos = DirName.rfind(PostFix);

	bool Valid = false;

	if ((pos >= 0) && (pos == str_len1 - str_len2))
	{
		Valid = true;
	}
	return Valid;
}

void SearchFilesInDir(wstring DirName, wstring PostFix, vector<wstring> & FileNameList)
{
	std::wstring pattern(DirName);

	pattern.append(L"\\*");

	WIN32_FIND_DATA data;
	HANDLE hFind;

	vector<wstring> FolderNameList;

	if ((hFind = FindFirstFile(pattern.c_str(), &data)) != INVALID_HANDLE_VALUE) {
		do {
			bool valid0 = !IsStringEndWithPostfix(data.cFileName, L".");
			if (valid0)
			{
				if (data.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY)
				{
					// is folder
					FolderNameList.push_back(DirName + L"\\" + data.cFileName);
				}
				else
				{
					// is file
					bool valid1 = IsStringEndWithPostfix(data.cFileName, PostFix);
					bool valid2 = IsStringEndWithPostfix(data.cFileName, L".tif");
					if (valid1 && valid2)
					{
						FileNameList.push_back(DirName + L"\\" + data.cFileName);
					}

//					wprintf(L"search file:%s\n",  data.cFileName);
				}
			}

		} while (FindNextFile(hFind, &data) != 0);
		FindClose(hFind);
	}

	// search sub-folders
	for (int i = 0; i < FolderNameList.size(); i++)
	{
		SearchFilesInDir(FolderNameList[i], PostFix, FileNameList);
	}
}



int main()
{
	wchar_t* str = L"G:\\test images";

	wstring DirName = str;
	wstring PostFix = L".tif";

	vector<wstring>  FileNameList;

	SearchFilesInDir(DirName, PostFix, FileNameList);


	int FileNumber = FileNameList.size();
	printf("file number:%d\n", FileNumber);


	CString CurStr;

	for (int cnt = 0; cnt < FileNumber; cnt++)
	{
		CurStr = FileNameList[cnt].c_str();
		wprintf(L"filename: %s\n", CurStr);
	}



	return 0;
}
wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==

参考了部分网上的代码

linux系统下文件搜索可以用popen等方式通过调用shell命令来实现。

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Luchang-Li

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值