std::filesystem::exists
來自 cppreference.com
< cpp | filesystem
定義於標頭檔案 <filesystem> |
||
bool exists( std::filesystem::file_status s ) noexcept; |
(1) | (C++17 起) |
bool exists( const std::filesystem::path& p ); |
(2) | (C++17 起) |
bool exists( const std::filesystem::path& p, std::error_code& ec ) noexcept; |
(3) | (C++17 起) |
檢查給定檔案狀態或路徑是否對應於現有檔案或目錄。
1) 等價於 status_known(s) && s.type() != file_type::not_found。
2,3) 令 s 為一個 std::filesystem::file_status,其確定方式分別如同 status(p) 或 status(p, ec)(符號連結被跟蹤)。返回 exists(s)。如果 status_known(s),非丟擲過載會呼叫 ec.clear()。
目錄 |
[編輯] 引數
s | - | 要檢查的檔案狀態 |
p | - | 要檢查的路徑 |
ec | - | 非丟擲過載中用於錯誤報告的出參 |
[編輯] 返回值
如果給定路徑或檔案狀態對應於現有檔案或目錄,則為 true,否則為 false。
[編輯] 異常
任何未標記為 noexcept
的過載都可能在記憶體分配失敗時丟擲 std::bad_alloc。
如果物件不存在(使用返回值),則不丟擲任何檔案系統異常。
[編輯] 注意
此函式提供的資訊通常也作為目錄迭代的副產品提供。在目錄迭代期間,呼叫 exists(*iterator) 的效率低於 exists(iterator->status())。
[編輯] 示例
執行此程式碼
#include <cstdint> #include <filesystem> #include <fstream> #include <iostream> namespace fs = std::filesystem; void demo_exists(const fs::path& p, fs::file_status s = fs::file_status{}) { std::cout << p; if (fs::status_known(s) ? fs::exists(s) : fs::exists(p)) std::cout << " exists\n"; else std::cout << " does not exist\n"; } int main() { const fs::path sandbox{"sandbox"}; fs::create_directory(sandbox); std::ofstream{sandbox/"file"}; // create regular file fs::create_symlink("non-existing", sandbox/"symlink"); demo_exists(sandbox); for (const auto& entry : fs::directory_iterator(sandbox)) demo_exists(entry, entry.status()); // use cached status from directory entry fs::remove_all(sandbox); }
輸出
"sandbox" exists "sandbox/symlink" does not exist "sandbox/file" exists
[編輯] 參閱
(C++17)(C++17) |
確定檔案屬性 確定檔案屬性,檢查符號連結目標 (函式) |
(C++17) |
表示檔案型別和許可權 (類) |
檢查目錄項是否引用現有檔案系統物件 ( std::filesystem::directory_entry 的公開成員函式) |