std::experimental::filesystem::exists
来自 cppreference.cn
< cpp | experimental | fs
定义于头文件 <experimental/filesystem> |
||
bool exists( file_status s ) |
(1) | (文件系统 TS) |
bool exists( const path& p ); bool exists( const path& p, error_code& ec ) |
(2) | (文件系统 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& 参数的重载会在底层 OS API 错误时抛出 filesystem_error,其中 p 作为第一个参数,OS 错误码作为错误码参数。如果内存分配失败,可能会抛出 std::bad_alloc。接受 error_code& 参数的重载在 OS API 调用失败时将其设置为 OS 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 的公有成员函数) |