Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::filesystem::exists: testing a known path status

std::filesystem::exists returns true when a path status is known and is not file_type::not_found.

Version: C++23

Syntax

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

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

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

std::filesystem::exists(p) from <filesystem> obtains status(p), so it follows a symbolic link by default, and tests status_known(s) && s.type() != file_type::not_found. A non-throwing overload also accepts an already obtained file_status.

The example creates a file, checks it and a missing path with the error_code overload, and prints 1 0 0: the file exists, the missing path does not, and ordinary absence left no error.

false does not always mean “certainly absent”: permission failure or another error can prevent status determination. With the ec overload inspect both the result and ec; when the status is known, the function clears ec. A dangling symlink gives false because status follows its target; use symlink_status plus exists(file_status) to test the link itself.

Examples

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

int main() {
    namespace fs = std::filesystem;
    const fs::path root = fs::temp_directory_path() / "cktis-cpp-ref-exists";
    const fs::path file = root / "item.txt";
    std::error_code ignored;
    fs::remove_all(root, ignored);
    fs::create_directory(root);
    std::ofstream(file) << "data";

    std::error_code ec;
    const bool present = fs::exists(file, ec);
    const bool missing = fs::exists(root / "missing.txt", ec);
    std::cout << present << ' ' << missing << ' ' << static_cast<bool>(ec) << '\n';

    fs::remove_all(root, ignored);
}

Result

1 0 0

std::filesystem::exists → 1 0 0

Sources