GSP
Quick Navigator

Search Site

Unix VPS
A - Starter
B - Basic
C - Preferred
D - Commercial
MPS - Dedicated
Previous VPSs
* Sign Up! *

Support
Contact Us
Online Help
Handbooks
Domain Status
Man Pages

FAQ
Virtual Servers
Pricing
Billing
Technical

Network
Facilities
Connectivity
Topology Map

Miscellaneous
Server Agreement
Year 2038
Credits
 

USA Flag

 

 

Man Pages
std::filesystem::directory_entry::exists(3) C++ Standard Libary std::filesystem::directory_entry::exists(3)

std::filesystem::directory_entry::exists - std::filesystem::directory_entry::exists


bool exists() const; (since C++17)
bool exists( std::error_code& ec ) const noexcept;


Checks whether the pointed-to object exists. Effectively returns
std::filesystem::exists(status()) or std::filesystem::exists(status(ec)),
respectively.


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


true if the referred-to filesystem object exists.


The overload that does not take a std::error_code& parameter throws
filesystem::filesystem_error on underlying OS API errors, constructed with p as the
first path argument and the OS error code as the error code argument. The overload
taking a std::error_code& parameter sets it to the OS API error code if an OS API
call fails, and executes ec.clear() if no errors occur. Any overload not marked
noexcept may throw std::bad_alloc if memory allocation fails.

// Run this code


#include <filesystem>
#include <fstream>
#include <iostream>
#include <string>


namespace fs = std::filesystem;


int main()
{
// store current path to restore it at exit
const auto old_current_path = fs::current_path();


// create "sanbox" directory in temp dir
const auto dir_sandbox = fs::temp_directory_path() / "sandbox";


if (!fs::create_directory(dir_sandbox)) {
std::cout << "ERROR #1" << '\n';
return -1;
}


fs::current_path(dir_sandbox); // switch to newly created dir


fs::directory_entry entry_sandbox { dir_sandbox };
if (!entry_sandbox.exists()) {
std::cout << "ERROR #2" << '\n';
return -1;
}


std::cout << "Current dir: " << entry_sandbox.path().filename() << '\n';


fs::path path_tmp_file = dir_sandbox / "tmp_file";


std::ofstream file( path_tmp_file.string() ); // create regular file
file << "cppreference.com"; // write 16 bytes
file.flush();


fs::directory_entry entry_tmp_file{ path_tmp_file };


if (entry_tmp_file.exists()) {
std::cout << "File " << entry_tmp_file.path().filename()
<< " has size: " << entry_tmp_file.file_size() << '\n';
} else {
std::cout << "ERROR #3" << '\n';
}


// cleanup
fs::current_path(old_current_path);
fs::remove_all(dir_sandbox);
}


Current dir: "sandbox"
File "tmp_file" has size: 16


exists checks whether path refers to existing file system object
(C++17) (function)

2022.07.31 http://cppreference.com

Search for    or go to Top of page |  Section 3 |  Main Index

Powered by GSP Visit the GSP FreeBSD Man Page Interface.
Output converted with ManDoc.