std::filesystem:: exists
|
定义于头文件
<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 起) |
检查给定的文件状态或路径是否对应存在的文件或目录。
目录 |
参数
| 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"}; // 创建常规文件 fs::create_symlink("non-existing", sandbox/"symlink"); demo_exists(sandbox); for (const auto& entry : fs::directory_iterator(sandbox)) demo_exists(entry, entry.status()); // 使用目录条目中的缓存状态 fs::remove_all(sandbox); }
输出:
"sandbox" exists "sandbox/symlink" does not exist "sandbox/file" exists
参见
|
(C++17)
(C++17)
|
确定文件属性
确定文件属性,检查符号链接目标 (函数) |
|
(C++17)
|
表示文件类型和权限
(类) |
|
检查目录项是否指向存在的文件系统对象
(
std::filesystem::directory_entry
的公开成员函数)
|