WissensdatenbankPrüfungszentrum
DEDeutsch
Sprache wählen13

CKTIS / C++

std::filesystem::copy: Dateisystemobjekte kopieren

std::filesystem::copy kopiert Datei, Symlink oder Verzeichnis nach Quelltyp und copy_options-Bits und meldet Fehler per Ausnahme oder 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) aus <filesystem> liefert void. Das voreingestellte copy_options::none kopiert reguläre Dateiinhalte, folgt symbolischen Links und kopiert bei Verzeichnissen unmittelbare Dateien, aber keine verschachtelten Unterverzeichnisse; copy_options::recursive aktiviert den vollständigen Abstieg.

Das Beispiel erstellt ein Quellverzeichnis mit a.txt, ruft copy mit recursive auf, liest die Kopie und gibt 1 data aus. Dies ist eine echte Dateisystemoperation; deshalb entfernt der Code sein privates Testverzeichnis vor und nach der Nutzung.

Aus jeder Optionsgruppe — vorhandenes Ziel, Rekursion, Symlinks und Kopierform — darf höchstens ein Bit gesetzt sein; eine verletzte Vorbedingung führt zu undefiniertem Verhalten. skip_existing, overwrite_existing und update_existing behandeln Ziele verschieden, copy_symlinks und skip_symlinks Links. Bei create_symlinks muss from absolut sein, sofern to nicht im aktuellen Verzeichnis liegt. Ist equivalent(from, to) true, meldet die Funktion einen Fehler; dies ist kein undefiniertes Verhalten der Optionsvorbedingung. Overloads ohne error_code können filesystem_error werfen; die ec-Form meldet Dateisystemfehler darüber.

Beispiele

#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);
}

Ergebnis

1 data

std::filesystem::copy → 1 data

Quellen