首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::filesystem::exists

Defined in header <filesystem>

bool exists( std::filesystem::file_status s )

(1)

(since C++17)

bool exists( const std::filesystem::path& p ); bool exists( const std::filesystem::path& p, std::error_code& ec )

(2)

(since C++17)

检查给定的文件状态或路径是否与现有文件或目录相对应。

1%29相当于status_known(s) && s.type() != file_type::not_found...

2%29相当于exists(status(p))exists(status(p, ec))%28符号链接跟随%29。非抛出重载返回。false如果发生错误。

参数

s

-

file status to check

p

-

path to examine

ec

-

out-parameter for error reporting in the non-throwing overload

返回值

true如果给定路径或文件状态对应于现有文件或目录,false否则。

例外

1%29

noexcept规格:

noexcept

2%29不占用std::error_code&参数抛文件系统[医]误差关于基础OS API错误,使用p作为第一个参数和操作系统错误代码作为错误代码参数。std::bad_alloc如果内存分配失败,则可能引发。过载std::error_code&参数,如果OSAPI调用失败,则将其设置为OSAPI错误代码,并执行ec.clear()如果没有错误发生。这个过载

noexcept规格:

noexcept

注记

此函数提供的信息通常也是目录迭代的副产品。在目录迭代期间,调用exists(*iterator)exists(iterator->status())...

二次

代码语言:javascript
复制
#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"); // 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");
}

二次

产出:

二次

代码语言:javascript
复制
"sandbox" exists
"sandbox/file" exists
"sandbox/symlink" does not exist

二次

另见

statussymlink_status (C++17)(C++17)

determines file attributesdetermines file attributes, checking the symlink target (function)

file_status (C++17)

represents file type and permissions (class)

statussymlink_status

status of the file designated by this directory entrysymlink_status of the file designated by this directory entry (public member function of std::filesystem::directory_entry)

代码语言:txt
复制
 © cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券