萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

C/C++ 判斷檔案或目錄是否存在的四種跨平台方法總整理

方法一:C++ fstream 嘗試開啟 (最簡單、純 C++、僅限檔案)

#include <fstream>
#include <iostream>
bool fileExists(const std::string& path) {
    std::ifstream f(path);
    return f.good(); // 或 f.is_open()
}

缺點:無法判斷目錄、需檔案讀取權限、符號連結行為視平台而定。

方法二:C 標準庫 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) 會回傳成功,無法區分檔案/目錄權限。

方法三:Windows API 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);
}

優點:可區分檔案/目錄、取得屬性 (隱藏、系統、唯讀)、支援長路徑 (\\?\ 前綴)。

方法四:Boost.Filesystem (跨平台、C++17 前標準做法)

#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)); // 遞迴建立多層目錄
}

C++17 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); }
  • GCC 8+ / Clang 7+ / MSVC 19.14+ 完整支援。
  • 編譯選項:-lstdc++fs (GCC < 9)、MSVC 自動連結。

四大方法選型指南

場景推薦方法理由
純 C++17+ 專案std::filesystem標準化、型別安全、功能完整
需支援 C++11/14、跨平台Boost.Filesystem成熟穩定、API 與 std::fs 幾乎相同
Windows 專屬、需屬性/長路徑Windows API原生效能、完整屬性控制
簡易檢查檔案、無依賴fstream / access()零依賴、程式碼極短
嵌入式/無標準庫環境平台原生 API體積最小

常見坑點

  • 競態條件 (TOCTOU):檢查存在 → 開啟 間隙檔案可能被刪除 → **直接嘗試開啟並處理錯誤** 更安全。
  • 符號連結:exists() 跟隨連結,lstat/GetFileAttributes 可檢測連結本身。
  • 權限:無讀取權限的目錄下檔案,access 回傳不存在,FindFirstFile 同樣失敗。
  • 路徑分隔符:跨平台統一用 /,Windows API 亦接受;std::filesystem::path 自動處理。

根據專案 C++ 標準版本、目標平台、功能需求選擇適當方法;現代專案首選 std::filesystem,舊專案以 Boost 或 Windows API 為備援。

copyright © 萬盛學電腦網 all rights reserved