std::filesystem::create_directory, std::filesystem::create_directories

Header: <filesystem>

1,2) Creates the directory p as if by POSIX mkdir() with a second argument of static_cast(std::filesystem::perms::all) (the parent directory must already exist). If the function fails because p resolves to an existing directory, no error is reported. Otherwise on failure an error is reported.

# Declarations

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

(since C++17)

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

(since C++17)

bool create_directory( const std::filesystem::path& p,
const std::filesystem::path& existing_p );

(since C++17)

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

(since C++17)

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

(since C++17)

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

(since C++17)

# Parameters

# Return value

true if a directory was newly created for the directory p resolves to, false otherwise.

# Notes

The attribute-preserving overload (3,4) is implicitly invoked by copy() when recursively copying directories. Its equivalent in boost.filesystem is copy_directory (with argument order reversed).

# Example

#include <cassert>
#include <cstdlib>
#include <filesystem>
 
int main()
{
    std::filesystem::current_path(std::filesystem::temp_directory_path());
 
    // Basic usage
    std::filesystem::create_directories("sandbox/1/2/a");
    std::filesystem::create_directory("sandbox/1/2/b");
 
    // Directory already exists (false returned, no error)
    assert(!std::filesystem::create_directory("sandbox/1/2/b"));
 
    // Permissions copying usage
    std::filesystem::permissions(
        "sandbox/1/2/b",
        std::filesystem::perms::others_all,
        std::filesystem::perm_options::remove
    );
    std::filesystem::create_directory("sandbox/1/2/c", "sandbox/1/2/b");
 
    std::system("ls -l sandbox/1/2");
    std::system("tree sandbox");
    std::filesystem::remove_all("sandbox");
}

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
LWG 2935C++17error if target already exists but is not a directorynot error
LWG 3014C++17error_code overload of create_directories marked noexcept but can allocate memorynoexcept removed
P1164R1C++17creation failure caused by an existing non-directory file is not an errormade error

# See also