std::filesystem::remove, std::filesystem::remove_all

Header: <filesystem>

1,2) The file or empty directory identified by the path p is deleted as if by the POSIX remove. Symlinks are not followed (symlink is removed, not its target).

# Declarations

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

(since C++17)

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

(since C++17)

std::uintmax_t remove_all( const std::filesystem::path& p );

(since C++17)

std::uintmax_t remove_all( const std::filesystem::path& p, std::error_code& ec );

(since C++17)

# Parameters

# Notes

On POSIX systems, this function typically calls unlink and rmdir as needed, on Windows DeleteFileW and RemoveDirectoryW.

If p did not exist, this function returns false and does not report an error.

# Example

#include <cstdint>
#include <filesystem>
#include <fstream>
#include <iostream>
 
int main()
{
    namespace fs = std::filesystem;
    std::cout << std::boolalpha;
 
    fs::path tmp{std::filesystem::temp_directory_path()};
 
    const auto O_O{"O_O"};
    std::ofstream{tmp / O_O} << O_O; // creates file containing O_O
    std::cout << "remove(): " << fs::remove(tmp / O_O) << '\n'; // success
    std::cout << "remove(): " << fs::remove(tmp / O_O) << '\n'; // fail
 
    std::filesystem::create_directories(tmp / "abcdef/example");
    const std::uintmax_t n{fs::remove_all(tmp / "abcdef")};
    std::cout << "remove_all(): " << n << " files or directories\n";
}

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
LWG 3014C++17error_code overload of remove_all marked noexcept but can allocate memorynoexcept removed

# See also