命名空间
变体
操作

std::experimental::filesystem::exists

来自 cppreference.cn
< cpp‎ | experimental‎ | fs
 
 
实验性
技术规范
文件系统库 (filesystem TS)
库基础 (library fundamentals TS)
库基础 2 (library fundamentals TS v2)
库基础 3 (library fundamentals TS v3)
并行扩展 (parallelism TS)
并行扩展 2 (parallelism TS v2)
并发扩展 (concurrency TS)
并发扩展 2 (concurrency TS v2)
概念 (concepts TS)
范围 (ranges TS)
反射 (reflection TS)
数学特殊函数 (special functions TR)
实验性非TS
模式匹配
线性代数
std::execution
契约
2D图形
 
 
定义于头文件 <experimental/filesystem>
bool exists( file_status s )
(1) (filesystem TS)
bool exists( const path& p );
bool exists( const path& p, error_code& ec )
(2) (filesystem TS)

检查给定的文件状态或路径是否对应于现有的文件或目录。

1) 等价于 status_known(s) && s.type() != file_type::not_found
2) 等价于 exists(status(p))exists(status(p, ec)) (符号链接会被跟随)。 无异常抛出的重载版本在发生错误时返回 false

内容

[编辑] 参数

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

[编辑] 返回值

true 如果给定的路径或文件状态对应于现有的文件或目录,则为 false 否则为。

[编辑] 异常

1)
noexcept 规范:  
noexcept
  
2) 不接受 error_code& 参数的重载版本会在底层操作系统 API 错误时抛出 filesystem_error 异常,该异常以 p 作为第一个参数,操作系统错误代码作为错误代码参数构造。 std::bad_alloc 如果内存分配失败,可能会抛出 异常。 接受 error_code& 参数的重载版本在操作系统 API 调用失败时将其设置为操作系统 API 错误代码,并在没有错误发生时执行 ec.clear()。 此重载版本具有
noexcept 规范:  
noexcept
  

[编辑] 注解

此函数提供的信息通常也作为目录迭代的副产品提供。 在目录迭代期间,调用 exists(*iterator)exists(iterator->status()) 效率低。

[编辑] 示例

#include <cstdint>
#include <experimental/filesystem>
#include <fstream>
#include <iostream>
namespace fs = std::experimental::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"); // create regular 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()); // use cached status from directory entry
    fs::remove_all("sandbox");
}

输出

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

[编辑] 参见

确定文件属性
确定文件属性,检查符号链接目标
(函数) [编辑]
表示文件类型和权限
(类) [编辑]
由此目录条目指定文件的缓存状态
由此目录条目指定文件的缓存符号链接状态
(std::experimental::filesystem::directory_entry 的公共成员函数) [编辑]