std::filesystem::exists
来自cppreference.com
                    
                                        
                    < cpp | filesystem
                    
                                                            
                    |   定义于头文件  <filesystem>
  | 
||
|   bool exists( std::filesystem::file_status s )  | 
(1) | (C++17 起) | 
|   bool exists( const std::filesystem::path& p ); bool exists( const std::filesystem::path& p, std::error_code& ec )  | 
(2) | (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 。
异常
2) 不接受 std::error_code& 参数的重载在底层 OS API 错误时抛出 filesystem_error ,以第一 path 参数 
p 和作为错误码参数的 OS 错误码构造。若 OS API 调用失败,则接受 std::error_code& 参数的重载设置该参数为 OS API 错误码,而若不出现错误则执行 ec.clear() 。若内存分配失败,则任何不标记为 noexcept 的重载可能抛出 std::bad_alloc 。注意
此函数提供的信息通常亦可作为目录迭代的副产物提供。在迭代中,调用 exists(*iterator) 的效率低于 exists(iterator->status())
示例
| 本节未完成 原因:切换到 directory_entry::exists  | 
运行此代码
#include <iostream> #include <fstream> #include <cstdint> #include <filesystem> 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() { fs::create_directory("sandbox"); std::ofstream("sandbox/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()); // 使用来自 directory_entry 的缓存状态 fs::remove_all("sandbox"); }
输出:
"sandbox" exists "sandbox/file" exists "sandbox/symlink" does not exist
参阅
|    (C++17)(C++17)  | 
  确定文件属性 确定文件属性,检查符号链接目标 (函数)  | 
|    (C++17)  | 
  表示文件类型及权限  (类)  | 
|   检查 directory_entry 是否代表既存文件系统对象  ( std::filesystem::directory_entry 的公开成员函数)  |