std::filesystem::exists_C++中文网

定义于头文件 <filesystem>

(1) (C++17 起)

bool exists( const std::filesystem::path& p );
bool exists( const std::filesystem::path& p, std::error_code& ec )

(2) (C++17 起)

检查给定的文件状态或路径是否对应已存在的文件或目录。

1) 等价于 status_known(s) && s.type() != file_type::not_found.

2)s 分别为如同以 status(p)status(p, ec) (跟随符号链接)确定的 std::filesystem::file_status 。返回 exists(s) 。若 status_known(s) 则不抛出重载调用 ec.clear()

参数

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

返回值

若给定路径或文件状态对应存在的文件或目录,则返回 true ,否则返回 false

异常

注意

此函数提供的信息通常亦可作为目录迭代的副产物提供。在迭代中,调用 exists(*iterator) 的效率低于 exists(iterator->status())

示例

本节未完成
原因:切换到 directory_entry::exists
#include <iostream>
#include <fstream>
#include <cstdint>
#include <filesystem>
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()
{
    fs::create_directory("sandbox");
    std::ofstream("sandbox/file"); // 创建常规文件
    fs::create_symlink("non-existing", "sandbox/symlink");
 
    demo_exists("sandbox");
    for(auto it = fs::directory_iterator("sandbox"); it != fs::directory_iterator(); ++it)
        demo_exists(*it, it->status()); // 使用来自 directory_entry 的缓存状态
    fs::remove_all("sandbox");
}

输出:

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

参阅