1、实现功能:简单实现文件遍历,输出文件夹和文件的目录,截图如下:
2、说明:没有利用tree控件的响应函数,tree控件只是用来简单的显示数据;
3、主要利用CStringArray和递归调用,经测试,遍历Win7系统目录用时20171 ms;
4、代码备份:
(1)tree控件初始化函数,其实就是往里添加路径数据:
int InitTreeControl(CString strRoot, HTREEITEM hTreeItemParent /*= NULL*/)
{
CStringArray strArrayFolderPath;
CStringArray strArrayFilePath;
HTREEITEM hTreeItemChild = NULL;
CString strParentData = L"";
CString strChildData = L"";
if (hTreeItemParent == NULL)
{
strParentData = strRoot;
hTreeItemParent = m_ctlTree.InsertItem(strParentData);
}
FileSearch(strRoot, strArrayFolderPath, strArrayFilePath);
for (int i = 0; i < strArrayFolderPath.GetSize(); i++)
{
strChildData = strArrayFolderPath.GetAt(i);
hTreeItemChild = m_ctlTree.InsertItem(strChildData, hTreeItemParent);
// 递归
InitTreeControl(strChildData, hTreeItemChild);
}
for (int i = 0; i < strArrayFilePath.GetSize(); i++)
{
strChildData = strArrayFilePath.GetAt(i);
hTreeItemChild = m_ctlTree.InsertItem(strChildData, hTreeItemParent);
}
return 0;
}
(2)FileSearch函数:
int FileSearch(CString strRootFolderPath, CStringArray& strArrayFolderPath, CStringArray& strArrayFilePath)
{
strArrayFolderPath.RemoveAll();
strArrayFilePath.RemoveAll();
int nChildFolderCounts = 0;
CFileFind ff;
CString FilePath;
if ( strRootFolderPath.Right(1) != _T("\\") )
{
strRootFolderPath += _T("\\");
}
strRootFolderPath += _T("*.*");
BOOL res = ff.FindFile(strRootFolderPath);
while (res)
{
res = ff.FindNextFile();
FilePath = ff.GetFilePath();
if (ff.IsDirectory() && !ff.IsDots())// 找到的是文件夹
{
strArrayFolderPath.Add(FilePath);
nChildFolderCounts++;
//FileSearch(FilePath, bFloderOrFile);// 不递归
}
else if (!ff.IsDirectory() && !ff.IsDots())// 找到的是文件
{
strArrayFilePath.Add(FilePath);
}
}
return nChildFolderCounts;
}
(3)变量说明;m_ctlTree是tree Control的控制变量,参数strRoot是根目录。
(4)可以添加一些风格:
m_ctlTree.ModifyStyle(NULL,TVS_HASBUTTONS | TVS_HASLINES | TVS_LINESATROOT);