MFC CFileFind 類別提供簡單易用的檔案搜尋介面,配合遞迴即可遍歷整棵目錄樹。本文說明專案設定、核心程式碼與常見陷阱。
#include <afx.h>(或 afxwin.h)。_T/LPCTSTR 混淆。void RecurseDirectory(LPCTSTR pszPath) {
CFileFind finder;
CString strWildcard(pszPath);
strWildcard += _T("\\*.*"); // 確保路徑結尾有反斜線
BOOL bWorking = finder.FindFile(strWildcard);
while (bWorking) {
bWorking = finder.FindNextFile();
if (finder.IsDots()) continue; // 跳過 "." 與 ".."
if (finder.IsDirectory()) {
CString subPath = finder.GetFilePath();
TRACE(_T("目錄: %s\n"), subPath);
RecurseDirectory(subPath); // 遞迴進入子目錄
} else {
// 處理檔案
TRACE(_T("檔案: %s\n"), finder.GetFilePath());
}
}
finder.Close();
}
// 呼叫範例
void PrintAllDirs() {
RecurseDirectory(_T("C:\\"));
}
FindNextFile() 才能使用 GetFileName()、GetFilePath() 等方法,否則會觸發斷言失敗。IsDots() 用於過濾當前目錄與父目錄,避免無限遞迴。TRACE 僅在 Debug 建置輸出,Release 會被移除;正式記錄請改用日誌庫。void IterateDirectory(LPCTSTR pszRoot) {
std::stack<CString> dirStack;
dirStack.push(pszRoot);
CFileFind finder;
while (!dirStack.empty()) {
CString curDir = dirStack.top(); dirStack.pop();
CString wildcard = curDir + _T("\\*.*");
BOOL bWorking = finder.FindFile(wildcard);
while (bWorking) {
bWorking = finder.FindNextFile();
if (finder.IsDots()) continue;
if (finder.IsDirectory()) {
dirStack.push(finder.GetFilePath());
} else {
// 處理檔案
}
}
finder.Close();
}
}