分类:
2008-10-14 14:57:22
遍历文件夹并建成目录树
作者:
HTREEITEM strRoot; //根目录 HTREEITEM strHTFir; //第一层 HTREEITEM strHTSec; //第二层 HTREEITEM strHtThi; //第三层 HTREEITEM strHtFor; //第四层 HTREEITEM strHtFif; //第五层 // 没有找到更好的方法,所以只能这样来显示,估计一下大约能用到几层,如果找到好方法,请告诉我,非常感谢! HTREEITEM strHtEnd; //文件目录(3)添加遍历文件夹的函数BrowseFile(int CallNum, CString strFile)
void CFileTreeDlg::BrowseFile(int CallNum, CString strFile) { CallNum++; CFileFind ff; CString szDir = strFile; if(szDir.Right(1) != "\\") szDir += "\\"; szDir += "*.*"; BOOL res = ff.FindFile(szDir); while(res) { res = ff.FindNextFile(); if(ff.IsDirectory() && !ff.IsDots())//目录是文件夹 { //如果是一个子目录,用递归继续往深一层找 CString strPath = ff.GetFilePath(); //得到路径,做为递归调用的开始 CString strTitle = ff.GetFileTitle();//得到目录名,做为树控的结点 int i =0; switch(CallNum) { case 1: strHTFir = m_FileTree.InsertItem(strTitle,0,0,NULL); break; case 2: strHTSec = m_FileTree.InsertItem(strTitle,0,0,strHTFir); break; case 3: strHtThi = m_FileTree.InsertItem(strTitle,0,0,strHTSec); break; case 4: strHtFor = m_FileTree.InsertItem(strTitle,0,0,strHtThi); break; default: strHtFif = m_FileTree.InsertItem(strTitle,0,0,strHtFor); break; } BrowseFile(CallNum,strPath);//递归调用 } else if(!ff.IsDirectory() && !ff.IsDots())//到达最低层的文件 { //显示当前访问的文件 CString strPath; CString strTitle; strPath = ff.GetFilePath(); strTitle = ff.GetFileTitle(); switch(CallNum) { case 1: strRoot = m_FileTree.InsertItem(strTitle,0,0,NULL); break; case 2: strHtEnd = m_FileTree.InsertItem(strTitle,0,0,strHTFir); break; case 3: strHtEnd = m_FileTree.InsertItem(strTitle,0,0,strHTSec); break; case 4: strHtEnd = m_FileTree.InsertItem(strTitle,0,0,strHtThi); break; case 5: strHtEnd = m_FileTree.InsertItem(strTitle,0,0,strHtFor); break; default: strHtEnd = m_FileTree.InsertItem(strTitle,0,0,strHtFif); break; } } } ff.Close();//关闭 }(4)在OnInitDialog()函数中设置树控件的图标并调用自定义函数BrowseFile()
BOOL CFileTreeDlg::OnInitDialog() { m_iImageList.Create(24, 24, TRUE,1, 0); //创建图标链 HICON hIcon = NULL; hIcon = (HICON)::LoadImage(::AfxGetInstanceHandle(), MAKEINTRESOURCE(IDI_KEBIAO), IMAGE_ICON, 24, 24, 0); m_iImageList.Add(hIcon); m_FileTree.SetImageList ( &m_iImageList,TVSIL_NORMAL ); BrowseFile(0,"课程表");//遍历"课程表"文件夹内的所有目录 }(全文完)