16,472
社区成员
发帖
与我相关
我的任务
分享
HANDLE hSearch;
WIN32_FIND_DATA FindData;
TCHAR szFile[MAX_PATH + 1];
hSearch = FindFirstFile(_T("*.*"), &FindData);
if (INVALID_HANDLE_VALUE != hSearch)
{
do
{
_tfullpath(szFile, FindData.cFileName, MAX_PATH);
TRACE(_T("%s\n"), szFile);
} while (FindNextFile(hSearch, &FindData));
FindClose(hSearch);
}
再看MFCCFileFind的实现源码
//FILEFIND.CPP
BOOL CFileFind::FindFile(LPCTSTR pstrName /* = NULL */,
DWORD dwUnused /* = 0 */)
{
……
Close();
m_pNextInfo = new WIN32_FIND_DATA;
……
m_hContext = ::FindFirstFile(pstrName, (WIN32_FIND_DATA*) m_pNextInfo);
……
}
BOOL CFileFind::FindNextFile()
{
ASSERT(m_hContext != NULL);
if (m_hContext == NULL)
return FALSE;
if (m_pFoundInfo == NULL)
m_pFoundInfo = new WIN32_FIND_DATA;
ASSERT_VALID(this);
void* pTemp = m_pFoundInfo;
m_pFoundInfo = m_pNextInfo;
m_pNextInfo = pTemp;
return ::FindNextFile(m_hContext, (LPWIN32_FIND_DATA) m_pNextInfo);
}
而CFileFind 类的与路径返回的都是基于m_pFoundInfo, 因此可以看出 CFileFind::FindNextFile() 中使用的是上次的搜索结果
因此上面等效的MFC的代码就是
CFileFind finder;
BOOL bWorking = finder.FindFile("*.*");
while (bWorking)
{
bWorking = finder.FindNextFile();
TRACE(_T("%s\n"), finder.GetFilePath());
}
//
void CDirDDlg::Find(CString FilePath)
{
CFileFind find;
BOOL bFound=find.FindFile(FilePath);
while (bFound)
{
bFound=find.FindNextFile();
CString text=find.GetFilePath();
afxDump << text << "\n";
if(find.IsDirectory())
{
if(!find.IsDots())
{
text+="\\*.*";
Find(text); //进行函数的递归调用
}
}
else
{
text+="\r\n";
m_file.Write(text,text.GetLength());
m_count++;
}
}
}
void CDirDDlg::OnButton1()
{
// TODO: Add your control notification handler code here
m_count=0;
char buf[512];
::GetCurrentDirectory(512,buf);
strcat(buf,"\\*.*");
m_file.Open("FIND.txt",CFile::modeCreate|CFile::modeReadWrite);
//
Find(buf);
//
m_file.Close(); //记着关闭文件
//
CString str;
str.Format("文件总数为%d",m_count);
MessageBox(str);
}
////////////////////////////////////////////////////////////////////
void CDirTreeCtrl::DisplayPath(HTREEITEM hParent, LPCTSTR strPath)
{// Displaying the Path in the TreeCtrl
CFileFind find;
CString strPathFiles = strPath;
BOOL bFind;
CSortStringArray strDirArray;
CSortStringArray strFileArray;
if ( strPathFiles.Right(1) != "\\" ) strPathFiles += "\\";
strPathFiles += "*.*";
bFind = find.FindFile( strPathFiles );
while ( bFind )
{
bFind = find.FindNextFile();
if ( find.IsDirectory() && !find.IsDots() )
{
strDirArray.Add( find.GetFilePath() );
}
if ( !find.IsDirectory() && m_bFiles ) strFileArray.Add( find.GetFilePath() );
}
strDirArray.Sort();
//
SetRedraw(FALSE);
CWaitCursor wait;
for ( int i = 0; i < strDirArray.GetSize(); i++ )
{
HTREEITEM hItem = AddItem( hParent, strDirArray.GetAt(i) );
if(FindSubDir(strDirArray.GetAt(i))) InsertItem("", 0, 0, hItem);
}
if ( m_bFiles )
{
strFileArray.Sort();
for ( i = 0; i < strFileArray.GetSize(); i++ )
{
HTREEITEM hItem = AddItem( hParent, strFileArray.GetAt(i) );
}
}
SetRedraw(TRUE);
//
}