VC显示指定路径下的所有文件及文件夹,所有的子文件夹。
本帖最后由 VisualEleven 于 2013-01-11 14:14:02 编辑
void CExerciseDlg::OnButtonShow()
{
CString strPath;
CEdit * pedit=(CEdit*)GetDlgItem(IDC_EDIT_PATH);
pedit->GetWindowText(strPath);
CFileFind finder;
BOOL existPath = finder.FindFile(strPath);
if(!existPath){
MessageBox("Path error");
}else{
m_listctrl.DeleteAllItems();
CFileFind tempFind;
if(strPath.Right(1) != "\\")
strPath += "\\";
strPath += "*.*";
BOOL res = tempFind.FindFile(strPath);
while( res )
{
res = tempFind.FindNextFile();
if(tempFind.IsDirectory() && !tempFind.IsDots())
{
strPath = tempFind.GetFilePath();
CString stra=strPath+"\\";
intnItem = m_listctrl.InsertItem(0xFFFF,stra);
}else if(!tempFind.IsDirectory() && !tempFind.IsDots())
{
strPath = tempFind.GetFilePath();
CFile file;
if (file.Open(strPath, CFile::modeRead))
{
int size = file.GetLength();
CString a;
a.Format("%d", size);
file.Close();
intnItem = m_listctrl.InsertItem(0xFFFF,strPath);
m_listctrl.SetItem(nItem,1,1,a,NULL,0,0,0);
}
}
}
tempFind.Close();
}
}
这个代码只实现了在指定文件夹下的文件和文件夹,想用回调的,但是没有实现,搞了很久都没搞出来,求指导,怎么改。
[解决办法]
和 回调 有半毛钱关系。你要的是 递归
[解决办法]
ULONGLONG CFileManager::CalcDirSize( const CString& strDirName)
{
CFileFind finder;
CString strDirFullName(strDirName);
strDirFullName += _T("\\*.*");
BOOL bRet = finder.FindFile(strDirFullName);
ULONGLONG nTotal = 0;
while (bRet)
{
bRet = finder.FindNextFile();
if (finder.IsDots())
{
continue;
}
else if (finder.IsDirectory())
{
nTotal += CalcDirSize(finder.GetFilePath());
}
else
{
nTotal += finder.GetLength();
}
}
finder.Close();
return nTotal;
}
计算指定目录大小的代码,楼主可以参考
[解决办法]
MSDN上关于CFileFind类有例子代码,你自己修改一下即可:
void Recurse(LPCTSTR pstr)
{
CFileFind finder;
// build a string with wildcards
CString strWildcard(pstr);
strWildcard += _T("\\*.*");
// start working for files
BOOL bWorking = finder.FindFile(strWildcard);
while (bWorking)
{
bWorking = finder.FindNextFile();
// skip . and .. files; otherwise, we'd
// recur infinitely!
if (finder.IsDots())
continue;
// if it's a directory, recursively search it
CString str = finder.GetFilePath();
TRACE(_T("%s\n"), (LPCTSTR)str);
if (finder.IsDirectory())
{
Recurse(str);
}
}
finder.Close();
}
void PrintDirs()
{
Recurse(_T("C:"));
}
[解决办法]
微软的CFileFind已经帮你实现了, 只需要用while循环就可以找到所有的,不需要递归.
和回调没什么关系.