现在的位置: 首页 > 综合 > 正文

遍历一个目录,使目录下的文件用树结构显示

2018年01月22日 ⁄ 综合 ⁄ 共 848字 ⁄ 字号 评论关闭

main函数:

ListDirectory(tstring(_T("D:\\test\\ListDir\\ListDir")));

函数:

void ListDirectory(tstring& fileName)
{
ListDir(fileName,0);
}

void ListDir(tstring& fileName,int depth)
{
tstring sFileFind(fileName);
sFileFind += _T("\\*.*");
WIN32_FIND_DATA fd;
HANDLE hFind = FindFirstFile(sFileFind.c_str(),&fd);
if(INVALID_HANDLE_VALUE == hFind)
return;
while(1)
{
if(fd.cFileName[0]!='.')
{
PrintName(tstring(fd.cFileName),depth);
if(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
tstring sFile(fileName);
sFile += _T("\\");
sFile += fd.cFileName;
ListDir(sFile,depth+1);
}
}
if(!FindNextFile(hFind,&fd))
break;
}
FindClose(hFind);
}

void PrintName(tstring& fileName,int depth)
{
for (int i=0;i<depth;i++)
{
tcout<<_T("    ");
}
tcout<<fileName<<endl;
}

FindFistFile:如果遍历一个目录下的所有子目录和文件,需要在该参数目录后面加\\*.*,如果只是获取该目录的信息(且不是根目录),则可以不用加\\*.*,FindFirstFile获取的是该目录的信息,但是之后调用FindNextFile会返回false。如果需要获取根目录的信息,需用调GetFileAttributes

抱歉!评论已关闭.