MFC CFileFind 封裝 Win32 FindFirstFile/FindNextFile,提供物件導向介面,支援萬用字元與遞迴遍歷。
#include
#include
using namespace std;
int main() {
if (SetCurrentDirectory(_T("D:\\Code\\POS"))) {
CFileFind finder;
BOOL bFound = finder.FindFile(_T("*.*"));
while (bFound) {
bFound = finder.FindNextFile();
if (finder.IsDots()) continue; // 跳過 . 和 ..
_tcout << finder.GetFileName() << endl;
// 完整路徑:finder.GetFilePath()
// 屬性:finder.IsDirectory(), GetLength(), GetCreationTime() 等
}
finder.Close();
}
return 0;
}
void ListAllFiles(LPCTSTR lpszDir) {
CFileFind finder;
CString strWildcard = lpszDir;
strWildcard += _T("\\*.*");
BOOL bFound = finder.FindFile(strWildcard);
while (bFound) {
bFound = finder.FindNextFile();
if (finder.IsDots()) continue;
if (finder.IsDirectory()) {
_tprintf(_T("[目錄] %s\n"), finder.GetFilePath());
ListAllFiles(finder.GetFilePath()); // 遞迴
} else {
_tprintf(_T(" [檔案] %s (%u bytes)\n"), finder.GetFilePath(), finder.GetLength());
}
}
finder.Close();
}
| 函式 | 說明 |
|---|---|
| FindFile(lpszName) | 開始搜尋,支援萬用字元 |
| FindNextFile() | 取得下一個,傳回 FALSE 表示結束 |
| GetFileName() | 僅檔名 |
| GetFilePath() | 完整路徑 |
| GetFileTitle() | 不含副檔名的檔名 |
| IsDirectory() | 是否為目錄 |
| IsDots() | 是否為 "." 或 ".." |
| GetLength() | 檔案大小 (位元組) |
| GetCreationTime/LastAccessTime/LastWriteTime(CTime&) | 時間屬性 |
| MatchesMask(dwMask) | 屬性遮罩檢查 (readonly, hidden, system...) |
Close() 釋放搜尋控制代碼。CString/TCHAR,配合 _tprintf 輸出。CFileFind 是 MFC 中處理檔案系統列舉的首選工具,語法簡潔、功能完整,配合遞迴即可輕鬆實現全盤掃描、檔案搜尋等需求。