C++ std::filesystem::copy_file
Copy a file to an independent destination before editing it.
A simple example
std::filesystem::copy_file
- Start with Source file containing A
- Do this Copy to a second file
- Result Both contain A
Syntax
fs::copy_file(original, copy)
Run these examples in C++
Save one example at a time as lesson.cpp. Use C++17 on macOS or Linux with a POSIX shell.
c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lessonKeep a separate copy of a receipt
A cashier gives a customer an annotated receipt and keeps the original for the daily ledger. Copy the saved receipt, add a note to the customer copy, and check what remains in the original.
#include <unistd.h>
#include <cstdlib>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <stdexcept>
namespace fs = std::filesystem;
int main() {
char pattern[] = "/tmp/file-lesson-XXXXXX";
if (!mkdtemp(pattern)) throw std::runtime_error("Cannot create workspace");
fs::path base(pattern);
try {
auto original = base / "original";
auto copy = base / "copy";
std::ofstream(original) << "paid";
fs::copy_file(original, copy);
std::ofstream(copy) << "collected";
std::string status;
std::ifstream(original) >> status;
std::cout << status << '\n';
} catch (...) {
fs::remove_all(base);
throw;
}
fs::remove_all(base);
}
paid
The original still contains only the payment status after the destination changes.
Prepare a gallery label
A curator stores a short UTF-8 caption beside an exhibit. Make a second copy for the afternoon shift. Which text does the new file contain?
Prepare a studio handover
A stage manager saves a two-word instruction for the next shift. Make a second copy for the afternoon shift. Which text does the new file contain?
What to watch for
Existing-destination and overwrite rules vary between APIs. This exercise uses a fresh destination.