名稱空間
變體
操作

std::filesystem::directory_entry::exists

來自 cppreference.com
 
 
 
 
bool exists() const;
(1) (C++17 起)
bool exists( std::error_code& ec ) const noexcept;
(2) (C++17 起)

檢查指向的物件是否存在。實際上返回

1) std::filesystem::exists(status())
2) std::filesystem::exists(status(ec))

注意 status() 會跟隨符號連結到其目標。

目錄

[編輯] 引數

ec - 非丟擲過載中用於錯誤報告的出參

[編輯] 返回值

true,如果引用的檔案系統物件存在。

[編輯] 異常

任何未標記為 noexcept 的過載都可能在記憶體分配失敗時丟擲 std::bad_alloc

1) 在底層 OS API 錯誤時丟擲 std::filesystem::filesystem_error,構造時以 p 作為第一個路徑引數,OS 錯誤碼作為錯誤碼引數。
2) 如果 OS API 呼叫失敗,則將 std::error_code& 引數設定為 OS API 錯誤碼;如果沒有發生錯誤,則執行 ec.clear()

[編輯] 示例

#include <filesystem>
#include <iostream>
 
int main()
{
    for (auto const str:
    {
        "/usr/bin/cat",
        "/usr/bin/mouse",
        "/usr/bin/python",
        "/usr/bin/bison",
        "/usr/bin/yacc",
        "/usr/bin/c++",
    })
    {
        std::filesystem::directory_entry entry{str};
 
        std::cout << "directory entry " << entry
                  << (entry.exists() ? " exists\n" : " does not exist\n");
    }
}

可能的輸出

// Output on a POSIX system:
directory entry "/usr/bin/cat" exist
directory entry "/usr/bin/mouse" does not exist
directory entry "/usr/bin/python" exists
directory entry "/usr/bin/bison" exists
directory entry "/usr/bin/yacc" does not exist
directory entry "/usr/bin/c++" exists

[編輯] 參閱

(C++17)
檢查路徑是否引用現有檔案系統物件
(函式) [編輯]