Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::filesystem::copy: copying filesystem objects

std::filesystem::copy copies a file, symlink, or directory according to the source type and copy_options bits, reporting errors by exception or error_code.

Version: C++23

Syntax

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

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

std::filesystem::copy(from, to, options) from <filesystem> returns void. Default copy_options::none copies regular-file content, follows symbolic links, and for a directory copies its immediate files but not nested subdirectories; copy_options::recursive enables the full descent.

The example creates a source directory with a.txt, calls copy with recursive, reads the copy, and prints 1 data. This is a real filesystem operation, so the code removes its private test directory before and after use.

At most one bit from each option group—existing target, recursion, symlinks, and copy form—may be set; violating that precondition is undefined behavior. skip_existing, overwrite_existing, and update_existing handle targets differently, while copy_symlinks and skip_symlinks change link handling. With create_symlinks, from must be absolute unless to is in the current directory. If equivalent(from, to) is true, the function reports an error—it is not undefined behavior from the option-group precondition. Overloads without error_code can throw filesystem_error; the ec form reports filesystem errors through ec.

Examples

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

int main() {
    namespace fs = std::filesystem;
    const fs::path root = fs::temp_directory_path() / "cktis-cpp-ref-copy";
    const fs::path source = root / "source";
    const fs::path target = root / "target";
    std::error_code ignored;
    fs::remove_all(root, ignored);
    fs::create_directories(source);
    std::ofstream(source / "a.txt") << "data";

    fs::copy(source, target, fs::copy_options::recursive);
    std::ifstream input(target / "a.txt");
    std::string text;
    input >> text;
    std::cout << fs::exists(target / "a.txt") << ' ' << text << '\n';
    fs::remove_all(root, ignored);
}

Result

1 data

std::filesystem::copy → 1 data

Sources