std::filesystem::exists
来自cppreference.com
< cpp | filesystem
在标头 <filesystem> 定义 | ||
bool exists(std::filesystem::file_status s )noexcept; | (1) | (C++17 起) |
bool exists(conststd::filesystem::path& p ); | (2) | (C++17 起) |
bool exists(conststd::filesystem::path& p, std::error_code& ec )noexcept; | (3) | (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。
[编辑]异常
若内存分配失败,则任何不标记为 noexcept
的重载可能抛出 std::bad_alloc 。
当对象不存在时并不抛出文件系统异常(使用返回值)。
[编辑]注解
此函数提供的信息通常亦可作为目录迭代的副产物提供。在迭代中,调用 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";elsestd::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(constauto& entry : fs::directory_iterator(sandbox)) demo_exists(entry, entry.status());// 使用来自 directory_entry 的缓存状态 fs::remove_all(sandbox);}
输出:
"sandbox" exists "sandbox/symlink" does not exist "sandbox/file" exists
[编辑]参阅
(C++17)(C++17) | 确定文件属性 确定文件属性,检查符号链接目标 (函数) |
(C++17) | 表示文件类型及权限 (类) |
检查 directory_entry 是否代表既存文件系统对象 ( std::filesystem::directory_entry 的公开成员函数) |