Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::filesystem::remove: removing one entry

std::filesystem::remove removes one file or empty directory and reports whether an existing entry was actually removed.

Version: C++23

Syntax

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

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

std::filesystem::remove(p) from <filesystem> acts as POSIX remove on the single entry named by p. It returns true when a file was removed and false when p did not exist; absence is not an error. It does not recursively erase directory contents.

The example creates a file, calls remove twice, and prints 1 0: the first call removes the entry and the second observes its absence. Use the separate remove_all for a whole tree; its result is the number of entries removed.

For a symbolic link, the link itself is removed, not its target. A nonempty directory, insufficient permission, or a filesystem failure is an error: the throwing overload can report filesystem_error, while the error_code& form is noexcept, returns false on error, and sets ec.

Examples

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

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

    const bool first = fs::remove(file);
    const bool second = fs::remove(file);
    std::cout << first << ' ' << second << '\n';

    fs::remove_all(root, ignored);
}

Result

1 0

std::filesystem::remove → 1 0

Sources