VC:遍历文件夹下所有文件和文件夹(CFileFind类、树视图控件、图像链表、HTREEITEM句柄、TV_INSERTSTRUCT 结构体)
1、添加变量:
HTREEITEM hDad;
HICON hIcon;
TV_INSERTSTRUCT tvinsert;
CImageList m_imagelist;
2、OnInitDialog()中初始化:
// TODO: Add extra initialization here
m_imagelist.Create(16,16,0,8,8);
hIcon=AfxGetApp()->LoadIcon(IDI_ICON1);
m_imagelist.Add(hIcon);
CTreeCtrl * pTree=(CTreeCtrl *)GetDlgItem(IDC_TREE);
pTree->SetImageList(&m_imagelist,TVSIL_NORMAL);
//开始显示树视图控件
tvinsert.hParent=NULL;
tvinsert.hInsertAfter=TVI_LAST;
tvinsert.item.mask=TVIF_IMAGE|TVIF_SELECTEDIMAGE|TVIF_TEXT;
tvinsert.item.hItem=NULL;
tvinsert.item.state=0;
tvinsert.item.stateMask=0;
tvinsert.item.cchTextMax=6;
tvinsert.item.iSelectedImage=1;
tvinsert.item.lParam=0;
//显示第一层
tvinsert.item.pszText="D:\\VC";
tvinsert.item.iImage=0;
tvinsert.item.iSelectedImage=0;
hDad=pTree->InsertItem(&tvinsert);
CString filepath="D:\\VC\\*.*";
//调用自定义函数:
Findfile(filepath,hDad);
3、添加自定义函数:
void CFileFindDlg::Findfile(CString str, HTREEITEM h)
{
CTreeCtrl * pTree=(CTreeCtrl *)GetDlgItem(IDC_TREE);
CFileFind filefind;
CString filepath=str;
CString filename;
tvinsert.hParent=h;
tvinsert.item.iImage=0;
tvinsert.item.iSelectedImage=0;
BOOL flag=filefind.FindFile(filepath);
while(flag)
{
flag=filefind.FindNextFile();
if(filefind.IsDots())
{
continue;
}
else
{
if(filefind.IsDirectory())
{
filename=filefind.GetFileName();
tvinsert.item.pszText=strdup(filename);
tvinsert.hParent=h;
hDad=pTree->InsertItem(&tvinsert);
Findfile(filefind.GetFilePath()+"\\*.*",hDad);//递归查找文件
}
else
{
tvinsert.hParent=h;
filename=filefind.GetFileName();
tvinsert.item.pszText=strdup(filename);
pTree->InsertItem(&tvinsert);
}
}
}
}