广度优先文件遍历 非递归 (Nonrecursive EnumFiles With Breadth-First Algo)

时间 : 

2013-01-30 11:18

摘要:

遍历一个指定文件夹下的所有文件,基于广度优先思想,也可认为是树形结构的层次遍历

编写背景:

在做Adobe Acrobat插件时收到一个需求,Adobe有一个菜单功能是让用户指定一个folder,然后把foler下的所有文件导入到pdf中,用户要求hook这个过程,当用户指定一个folder时,判断folder下是否有敏感文件,如果有则取消本次操作。

个人感觉对于这样的需求,使用广度优先算法,找到敏感文件的时间必少于深度优先。

代码:

bool EnumFiles_Breadth_Fisrt(string RootFolder,bool (*DoWork)(string curFile))  //Level traversal ,
{
	// need RootFolder  optimization
	//optimization RootFolder
	if (!iends_with(RootFolder,"\\")) RootFolder+="\\"; 
	DWORD dw=::GetFileAttributesA(RootFolder.c_str() );
	if(  !(dw&FILE_ATTRIBUTE_DIRECTORY) )return  false;  // Folder only
	// Currently Find *.*
	queue<string> runtimeQueue;  //each node is path+filetpye
	runtimeQueue.push(RootFolder+"*.*");
	//Breadth-first
	do 
	{
		WIN32_FIND_DATAA fd;
		string curSearchPattern(runtimeQueue.front()); // current FindFileTpye
		string curfolder=curSearchPattern.substr(0,curSearchPattern.find_last_of('\\')+1);
		//	cout<<curfolder.c_str()<<endl;
		HANDLE hFind = ::FindFirstFileA(curSearchPattern.c_str(),&fd);	
		if (INVALID_HANDLE_VALUE == hFind  )	return false;

		do
		{
			if (fd.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)
			{
				if( !iequals(fd.cFileName,".") && !iequals(fd.cFileName,"..") )
				{
					string internalfolder(curfolder+fd.cFileName+"\\"); //a sub Folder
					runtimeQueue.push(internalfolder+"*.*");	//currently find type
				}
			}
			else
			{
				if(false==(*DoWork)(curfolder+fd.cFileName)) return false;
			}
		}while(FindNextFileA(hFind,&fd));
		runtimeQueue.pop();
		FindClose(hFind);
	} while (!runtimeQueue.empty());
	return true;

}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值