首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

MFC CFileFind 類完整指南:文件搜尋、屬性獲取與實戰技巧

     編輯:關於C語言

一、CFileFind 概覽

CFileFind 是 MFC 提供的本地文件搜尋類,聲明於 afx.h。它是 CGopherFileFind 和 CFtpFileFind 的基類,專門用於:

  • 查找特定文件(如 test.txt)
  • 按模式查找(如 *.cpp、data?.log)
  • 遍歷目錄下所有文件(*.*)

二、核心成員函數分類

1. 搜尋操作類

函數說明
BOOL FindFile(LPCTSTR pstrName = NULL, DWORD dwUnused = 0)開始搜尋,pstrName 為搜尋模式,預設 *.*。成功返回非 0。
BOOL FindNextFile()獲取下一個匹配項。還有結果返回非 0,結束返回 0。

2. 文件屬性獲取類(需先調用 FindNextFile)

函數返回值範例
GetCreationTimeBOOL(輸出 FILETIME* 或 CTime&)文件創建時間
GetLastAccessTimeBOOL最後訪問時間
GetLastWriteTimeBOOL最後修改時間
GetFileNameCStringtest.txt
GetFileTitleCStringtest(無擴展名)
GetFilePathCStringC:\Data\test.txt
GetRootCStringC:\Data\
GetFileURLCStringfile://C:/Data/test.txt
GetLengthDWORD文件大小(位元組)

3. 文件屬性判斷類(返回 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

七、常見坑點提醒

  1. 忘記 Close():導致句柄泄漏,後續搜尋失敗。
  2. 在 FindNextFile 前調用屬性函數:返回無效數據或斷言失敗。
  3. 路徑分隔符:MFC 接受 \\ 或 /,但拼接時統一用 \\ 更安全。
  4. 大小寫敏感:Windows 文件系統不區分大小寫,但 MatchesMask 依賴屬性位而非名稱。

掌握 CFileFind,即可輕鬆實現文件掃描、清理、同步、索引等常見需求。配合 CTime、CString 可構建功能豐富的文件管理模組。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved