#include <fstream>
#include <iostream>
bool fileExists(const std::string& path) {
std::ifstream f(path);
return f.good(); // 或 f.is_open()
}
缺點:無法判斷目錄、需檔案讀取權限、符號連結行為視平台而定。
access() / _access() (POSIX/Windows 通用)#include <io.h> // Windows _access
#include <unistd.h> // POSIX access
bool exists(const char* path) {
#ifdef _WIN32
return _access(path, 0) == 0; // 0 = F_OK 僅檢查存在
#else
return access(path, F_OK) == 0;
#endif
}
mode 參數:0(存在)、2(寫入)、4(讀取)、6(讀寫)。
注意:Windows 目錄皆視為可讀寫,access(dir, 2) 會回傳成功,無法區分檔案/目錄權限。
FindFirstFile / GetFileAttributes (Windows 專用、功能最全)#include <windows.h>
bool fileExistsWin(const std::wstring& path) {
WIN32_FIND_DATAW data;
HANDLE h = FindFirstFileW(path.c_str(), &data);
if (h == INVALID_HANDLE_VALUE) return false;
FindClose(h);
return !(data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
}
bool dirExistsWin(const std::wstring& path) {
DWORD attr = GetFileAttributesW(path.c_str());
return (attr != INVALID_FILE_ATTRIBUTES) && (attr & FILE_ATTRIBUTE_DIRECTORY);
}
優點:可區分檔案/目錄、取得屬性 (隱藏、系統、唯讀)、支援長路徑 (\\?\ 前綴)。
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
bool existsBoost(const std::string& path) {
return fs::exists(fs::path(path, fs::native));
}
bool isDirectory(const std::string& path) {
return fs::is_directory(fs::path(path, fs::native));
}
void createDirs(const std::string& path) {
fs::create_directories(fs::path(path, fs::native)); // 遞迴建立多層目錄
}
std::filesystem (現代標準、零依賴)#include <filesystem>
namespace fs = std::filesystem;
bool exists(const std::string& path) { return fs::exists(path); }
bool isDir(const std::string& path) { return fs::is_directory(path); }
bool isFile(const std::string& path) { return fs::is_regular_file(path); }
void createDirs(const std::string& path) { fs::create_directories(path); }
-lstdc++fs (GCC < 9)、MSVC 自動連結。| 場景 | 推薦方法 | 理由 |
|---|---|---|
| 純 C++17+ 專案 | std::filesystem | 標準化、型別安全、功能完整 |
| 需支援 C++11/14、跨平台 | Boost.Filesystem | 成熟穩定、API 與 std::fs 幾乎相同 |
| Windows 專屬、需屬性/長路徑 | Windows API | 原生效能、完整屬性控制 |
| 簡易檢查檔案、無依賴 | fstream / access() | 零依賴、程式碼極短 |
| 嵌入式/無標準庫環境 | 平台原生 API | 體積最小 |
exists() 跟隨連結,lstat/GetFileAttributes 可檢測連結本身。access 回傳不存在,FindFirstFile 同樣失敗。/,Windows API 亦接受;std::filesystem::path 自動處理。根據專案 C++ 標準版本、目標平台、功能需求選擇適當方法;現代專案首選 std::filesystem,舊專案以 Boost 或 Windows API 為備援。