Namespaces
Variants

std::filesystem:: exists

From cppreference.net
定义于头文件 <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 为通过 status ( p ) status ( p, ec ) (跟随符号链接)分别确定的 std:: filesystem :: file_status 。返回 exists ( s ) 。非抛出重载在 status_known ( s ) 时调用 ec. clear ( )

目录

参数

s - 要检查的文件状态
p - 要检查的路径
ec - 非抛出重载中用于错误报告的输出参数

返回值

true 如果给定路径或文件状态对应已存在的文件或目录, false 则表示其他情况。

异常

任何未标记为 noexcept 的重载在内存分配失败时可能抛出 std::bad_alloc

2) 当底层操作系统 API 出错时抛出 std::filesystem::filesystem_error ,该异常以 p 作为第一个路径参数,以操作系统错误代码作为错误码参数构造。
3) 若操作系统API调用失败,将 std:: error_code & 参数设置为操作系统API错误码;若未发生错误,则执行 ec. clear ( )

如果对象不存在,不会抛出文件系统异常(请使用返回值)。

注释

该函数提供的信息通常也会作为目录迭代的副产品获得。在目录迭代期间,调用 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"}; // 创建常规文件
    fs::create_symlink("non-existing", sandbox/"symlink");
    demo_exists(sandbox);
    for (const auto& entry : fs::directory_iterator(sandbox))
        demo_exists(entry, entry.status()); // 使用目录条目中的缓存状态
    fs::remove_all(sandbox);
}

输出:

"sandbox" exists
"sandbox/symlink" does not exist
"sandbox/file" exists

参见

(C++17) (C++17)
确定文件属性
确定文件属性,检查符号链接目标
(函数)
表示文件类型和权限
(类)
检查目录项是否指向存在的文件系统对象
( std::filesystem::directory_entry 的公开成员函数)