檔案系統操作是程式開發的基礎需求。本文介紹兩種截然不同風格的解決方案:boost::filesystem 提供現代化、跨平台、STL 風格的介面;Windows Shell Path Functions(Shlwapi.h/.lib)則是輕量級、原生、功能豐富的路徑字串處理工具箱。
核心類別:path(路徑表示)、directory_iterator(目錄迭代)、file_status(狀態查詢)。
#include <boost/filesystem.hpp>
#include <string>
using namespace boost::filesystem;
bool find_file(const path& dir_path, const std::string& file_name) {
if (!exists(dir_path)) return false;
for (directory_iterator itr(dir_path), end; itr != end; ++itr) {
if (is_directory(*itr)) {
if (find_file(*itr, file_name)) return true; // 遞迴進入子目錄
} else if (itr->path().leaf() == file_name) { // leaf() 取檔名/目錄名
return true;
}
}
return false;
}
關鍵點:
path 時加 native 標記:path p("C:\\", native);。directory_iterator 預設建構為 end iterator,配合範圍 for 或 while 迴圈極為直觀。copy_file、rename、remove、create_directory 等高階操作,自動處理平台差異。位於 Shlwapi.dll,標頭 Shlwapi.h,連結 Shlwapi.lib。超過 50 個函數涵蓋路徑組合、解析、正規化、URL 處理、相對/絕對轉換等。
常用函數速查:
| 函數 | 用途 |
|---|---|
PathCombine | 安全組合目錄與檔名,自動處理反斜線 |
PathFindFileName | 從完整路徑取得檔名部分 |
PathRemoveFileSpec | 移除檔名,保留目錄路徑 |
PathAddBackslash | 確保路徑以反斜線結尾 |
PathIsDirectory | 快速判斷路徑是否為現有目錄 |
PathFileExists | 判斷檔案/目錄是否存在 |
PathMatchSpec | 支援萬用字元的檔名比對 |
PathCreateFromUrl / PathGetCharType | URL 與本地路徑互轉 |
boost::filesystem(C++17 已納入標準庫 std::filesystem)。Shlwapi 函數更直接、無額外依賴、二進位體積極小。filesystem,路徑字串細節處理呼叫 PathXxx。善用現有庫,避免重複造輪子,專注於業務邏輯創新。