遍历文件夹及其子文件夹下所有文件

#include <WINDOWS.H>
#include <IOSTREAM.H>
#include <STRING>

using namespace std;


void g_EnumFile(char* path,int depth)
{
	string strPath=path;
	//设置通配符,这里*.*搜索所有文件
	strPath+="\\*.*";
	WIN32_FIND_DATA fd;
	HANDLE hFile=::FindFirstFile(strPath.c_str(),&fd);
	if(hFile==INVALID_HANDLE_VALUE)
		return;
	
	while(true)
	{
		//跳过名为'.'和'..'的文件
		if (fd.cFileName[0]!='.')
		{
			//如果是目录,递归遍历
			if (fd.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)
			{
				string nextPath=path;
				nextPath+="\\";
				nextPath+=fd.cFileName;
				g_EnumFile((char*)nextPath.c_str(),depth+1);
			}
			else//不是目录
			{
				//输出目录层次的缩进
				for(int i=0;i<depth;i++)
					cout<<"    ";
				cout<<path<<"\\"<<fd.cFileName<<endl;
			}
		}
		if(::FindNextFile(hFile,&fd)==0)
				break;
	}
	::FindClose(hFile);
}
int main()
{
	char currentDir[MAX_PATH]={0};
	::GetCurrentDirectory(sizeof(currentDir),currentDir);
	g_EnumFile(currentDir,0);
	return 0;
}
遍历文件夹及其子文件夹下所有文件_第1张图片

你可能感兴趣的:(遍历文件夹及其子文件夹下所有文件)