CFileFind 是 MFC 提供的本地文件搜尋類,聲明於 afx.h。它是 CGopherFileFind 和 CFtpFileFind 的基類,專門用於:
test.txt)*.cpp、data?.log)*.*)| 函數 | 說明 |
|---|---|
BOOL FindFile(LPCTSTR pstrName = NULL, DWORD dwUnused = 0) | 開始搜尋,pstrName 為搜尋模式,預設 *.*。成功返回非 0。 |
BOOL FindNextFile() | 獲取下一個匹配項。還有結果返回非 0,結束返回 0。 |
FindNextFile)| 函數 | 返回值 | 範例 |
|---|---|---|
GetCreationTime | BOOL(輸出 FILETIME* 或 CTime&) | 文件創建時間 |
GetLastAccessTime | BOOL | 最後訪問時間 |
GetLastWriteTime | BOOL | 最後修改時間 |
GetFileName | CString | test.txt |
GetFileTitle | CString | test(無擴展名) |
GetFilePath | CString | C:\Data\test.txt |
GetRoot | CString | C:\Data\ |
GetFileURL | CString | file://C:/Data/test.txt |
GetLength | DWORD | 文件大小(位元組) |
BOOL,非 0 為真)IsDirectory()、IsDots()(. 或 ..)、IsHidden()、IsReadOnly()、IsSystem()、IsArchived()、IsCompressed()、IsTemporary()、IsNormal()MatchesMask(DWORD dwMask):組合屬性判斷,dwMask 可用 FILE_ATTRIBUTE_* 常量按位或組合。CFileFind finder;
BOOL bFound = finder.FindFile(_T("C:\\Data\\*.*")); // 1. 開始搜尋
while (bFound) {
bFound = finder.FindNextFile(); // 2. 獲取下一個
if (bFound) {
// 3. 此處可安全調用屬性獲取/判斷函數
if (!finder.IsDots() && !finder.IsDirectory()) {
CString name = finder.GetFileName();
DWORD size = finder.GetLength();
// 處理文件...
}
}
}
finder.Close(); // 4. 必須關閉釋放句柄
// FILETIME -> CTime
FILETIME ft;
finder.GetCreationTime(&ft);
CTime ct(ft); // 直接構造
// 或經過 SYSTEMTIME
SYSTEMTIME st;
FileTimeToSystemTime(&ft, &st);
CTime ct2(st);
// CTime -> FILETIME
CTime now = CTime::GetCurrentTime();
SYSTEMTIME st2;
now.GetAsSystemTime(st2);
FILETIME ft2;
SystemTimeToFileTime(&st2, &ft2);
CFileFind ff;
CString strDir = _T("D:\\Projects");
if (strDir.Right(1) != _T("\\")) strDir += _T("\\");
strDir += _T("*.*");
BOOL bRes = ff.FindFile(strDir);
while (bRes) {
bRes = ff.FindNextFile();
if (ff.IsDots() || ff.IsDirectory()) continue; // 跳過目錄
CString path = ff.GetFilePath();
CString name = ff.GetFileName();
CString title = ff.GetFileTitle();
CString ext = name.Mid(name.ReverseFind('.') + 1);
CString url = ff.GetFileURL();
CString root = ff.GetRoot();
DWORD len = ff.GetLength();
CString msg;
msg.Format(_T("Path: %s\nName: %s\nTitle: %s\nExt: %s\nURL: %s\nRoot: %s\nSize: %u\n\n"),
path, name, title, ext, url, root, len);
OutputDebugString(msg);
}
ff.Close();
TRY {
CopyFile(strFullName, strBackupDir + strFileName, FALSE); // 不覆蓋
DeleteFile(strFullName); // 刪除源文件
}
CATCH(CFileException, pEx) {
AfxMessageBox(_T("備份失敗"));
pEx->Delete();
}
END_CATCH
Close():導致句柄泄漏,後續搜尋失敗。FindNextFile 前調用屬性函數:返回無效數據或斷言失敗。\\ 或 /,但拼接時統一用 \\ 更安全。MatchesMask 依賴屬性位而非名稱。掌握 CFileFind,即可輕鬆實現文件掃描、清理、同步、索引等常見需求。配合 CTime、CString 可構建功能豐富的文件管理模組。