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

VC++ 遞迴遍歷目錄下所有檔案:CFileFind 實戰範例

     編輯:關於VC++

核心類別:CFileFind

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() 釋放搜尋控制代碼。
  • 遞迴深度過大可能導致堆疊溢位,極深目錄樹建議改用堆疊模擬遞迴。
  • Unicode 專案下所有字串均為 CString/TCHAR,配合 _tprintf 輸出。

總結

CFileFind 是 MFC 中處理檔案系統列舉的首選工具,語法簡潔、功能完整,配合遞迴即可輕鬆實現全盤掃描、檔案搜尋等需求。

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