std::filesystem::copy

Header: <filesystem>

Copies files and directories, with a variety of options.

# Declarations

void copy( const std::filesystem::path& from,
const std::filesystem::path& to );

(since C++17)

void copy( const std::filesystem::path& from,
const std::filesystem::path& to,
std::error_code& ec );

(since C++17)

void copy( const std::filesystem::path& from,
const std::filesystem::path& to,
std::filesystem::copy_options options );

(since C++17)

void copy( const std::filesystem::path& from,
const std::filesystem::path& to,
std::filesystem::copy_options options,
std::error_code& ec );

(since C++17)

# Parameters

# Return value

(none)

# Notes

The default behavior when copying directories is the non-recursive copy: the files are copied, but not the subdirectories:

While with copy_options::recursive, the subdirectories are also copied, with their content, recursively.

# Example

#include <cstdlib>
#include <filesystem>
#include <fstream>
#include <iostream>
namespace fs = std::filesystem;
 
int main()
{
    fs::create_directories("sandbox/dir/subdir");
    std::ofstream("sandbox/file1.txt").put('a');
    fs::copy("sandbox/file1.txt", "sandbox/file2.txt"); // copy file
    fs::copy("sandbox/dir", "sandbox/dir2"); // copy directory (non-recursive)
    const auto copyOptions = fs::copy_options::update_existing
                           | fs::copy_options::recursive
                           | fs::copy_options::directories_only
                           ;
    fs::copy("sandbox", "sandbox_copy", copyOptions); 
    static_cast<void>(std::system("tree"));
    fs::remove_all("sandbox");
    fs::remove_all("sandbox_copy");
}

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
LWG 3013C++17error_code overload marked noexcept but can allocate memorynoexcept removed
LWG 2682C++17attempting to create a symlink for a directory succeeds but does nothingreports an error

# See also