CKTIS / C++
std::filesystem::copy: bestandssysteemobjecten kopiëren
std::filesystem::copy kopieert een bestand, symbolische link of map volgens brontype en copy_options-bits en meldt fouten via exceptie of error_code.
Versie: 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) uit <filesystem> retourneert void. Standaard copy_options::none kopieert gewone bestandsinhoud, volgt symbolische links en kopieert bij een map de directe bestanden maar geen geneste submappen; copy_options::recursive schakelt volledige afdaling in.
Het voorbeeld maakt een bronmap met a.txt, roept copy aan met recursive, leest de kopie en print 1 data. Dit is een echte bestandssysteembewerking, dus de code verwijdert zijn eigen testmap vóór en na gebruik.
Per optiegroep — bestaand doel, recursie, links en kopievorm — mag hoogstens één bit zijn gezet; schending van die preconditie is ongedefinieerd gedrag. skip_existing, overwrite_existing en update_existing behandelen doelen anders, terwijl copy_symlinks en skip_symlinks links wijzigen. Bij create_symlinks moet from absoluut zijn, tenzij to in de huidige map staat. Als equivalent(from, to) true is, meldt de functie een fout; dit is niet het ongedefinieerde gedrag van de optiepreconditie. Overloads zonder error_code kunnen filesystem_error werpen; de ec-vorm meldt bestandssysteemfouten via ec.
Voorbeelden
#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);
}
Resultaat
1 data
std::filesystem::copy → 1 data