std::filesystem::exists
来自 cppreference.cn
< cpp | filesystem
| 定义于头文件 <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 为一个 std::filesystem::file_status,其确定方式分别如同 status(p) 或 status(p, ec)(符号链接被跟踪)。返回 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"; else std::cout << " does not exist\n"; } int main() { const fs::path sandbox{"sandbox"}; fs::create_directory(sandbox); std::ofstream{sandbox/"file"}; // create regular file fs::create_symlink("non-existing", sandbox/"symlink"); demo_exists(sandbox); for (const auto& entry : fs::directory_iterator(sandbox)) demo_exists(entry, entry.status()); // use cached status from directory entry fs::remove_all(sandbox); }
输出
"sandbox" exists "sandbox/symlink" does not exist "sandbox/file" exists
[编辑] 参阅
| (C++17)(C++17) |
确定文件属性 确定文件属性,检查符号链接目标 (函数) |
| (C++17) |
表示文件类型和权限 (类) |
| 检查目录项是否引用现有文件系统对象 ( std::filesystem::directory_entry 的公开成员函数) |