Namespaces
Variants

std::filesystem::directory_entry:: exists

From cppreference.net
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) 当底层操作系统API出错时抛出 std::filesystem::filesystem_error ,该异常以 p 作为第一个路径参数,以操作系统错误代码作为错误码参数构造。
2) 若操作系统API调用失败,将 std:: error_code & 参数设置为操作系统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");
    }
}

可能的输出:

// 在POSIX系统上的输出:
directory entry "/usr/bin/cat" 存在
directory entry "/usr/bin/mouse" 不存在
directory entry "/usr/bin/python" 存在
directory entry "/usr/bin/bison" 存在
directory entry "/usr/bin/yacc" 不存在
directory entry "/usr/bin/c++" 存在

参见

(C++17)
检查路径是否指向存在的文件系统对象
(函数)