Copy File in C++
Copy a file in C++ two ways: std::filesystem::copy_file with error handling, and a manual stream copy with rdbuf(). Then verify by comparing file sizes.
1#include <iostream>2#include <fstream>3#include <filesystem>4using namespace std;5using namespace filesystem;67int main() {8 string sourceFile = "data.txt";9 string destFile = "data_copy.txt";1011 // Method 1: Using filesystem (C++17) - Simple12 try {13 copy_file(sourceFile, destFile);14 cout << "File copied successfully using filesystem!" << endl;15 } catch (const filesystem_error& e) {16 cout << "Error: " << e.what() << endl;17 }1819 // Method 2: Manual copy - Read and write20 ifstream source(sourceFile, ios::binary);21 ofstream dest(destFile + "_manual", ios::binary);2223 if (source.is_open() && dest.is_open()) {24 dest << source.rdbuf(); // Copy entire file buffer2526 source.close();27 dest.close();2829 cout << "File copied manually!" << endl;30 } else {31 cout << "Error opening files for manual copy." << endl;32 }3334 // Verify copy35 if (exists(destFile)) {36 cout << "\nVerification:" << endl;37 cout << "Source size: " << file_size(sourceFile) << " bytes" << endl;38 cout << "Copy size: " << file_size(destFile) << " bytes" << endl;3940 if (file_size(sourceFile) == file_size(destFile)) {41 cout << "File sizes match - Copy verified!" << endl;42 }43 }4445 return 0;46}
Sample Output
File sizes match - Copy verified!
Both files are 146 bytes in this run.
In this one
- How copy_file works and when it throws
- How to overwrite with copy_options
- How rdbuf() copies a whole stream
- How to sanity-check a copy by size
How it works
- 1
Try copy_file(data.txt, data_copy.txt) and catch filesystem_error.
- 2
Open source and data_copy.txt_manual in binary mode.
- 3
dest << source.rdbuf() copies everything.
- 4
If the copy exists, compare file sizes.
Edge cases
Destination already exists
Run the program twice.
copy_file throws because overwriting is off by default, so "Error: ..." prints. The manual copy still runs and overwrites its own file.
Source missing
Delete data.txt.
copy_file throws, the manual open fails, and exists(destFile) may still be true from an earlier run, in which case file_size on the missing source throws and the program terminates.
What's going on
This program copies data.txt two ways and then checks that the copy has the same size. Like file-check-exists, it uses <filesystem> and needs C++17.
Method 1 is one call: copy_file(sourceFile, destFile). It is wrapped in try-catch because it throws filesystem_error when something goes wrong, for example when data.txt is missing. It also throws when data_copy.txt already exists, because the default is to refuse to overwrite. So the first run prints "File copied successfully", and a second run prints an "Error: ... File exists" message instead. Pass copy_options::overwrite_existing as a third argument to allow replacing it.
Method 2 copies by hand. It opens the source and a second destination, data_copy.txt_manual, both in binary mode so no newline translation happens. dest << source.rdbuf(); is a neat shortcut: rdbuf() returns the source's stream buffer, and inserting a buffer into an output stream copies everything from it until the end. No loop is needed.
The verification block calls exists(destFile), then compares file_size of the source and the copy. Matching sizes are a quick sanity check, not proof the bytes match; a full check would compare contents.
The sample sizes are 146 bytes, the size of data.txt after file-write and file-append each ran once on Linux or macOS.
The headers come first. <iostream> is there because it provides cout and cin for input/output operations. <fstream> is there because it provides file stream classes (ifstream, ofstream). <filesystem> is there because it provides filesystem operations (C++17). Leave one out and the compiler stops at the first name it does not recognize.
Understanding File Copying
Copy Concept:
Copy Methods:
Method 1: Using filesystem::copy_file()
Simple Copy:
copy_file(sourceFile, destFile);
What happens here:
Error Handling:
try {
copy_file(sourceFile, destFile);
} catch (const filesystem_error& e) {
cout << "Error: " << e.what() << endl;
}
Method 2: Manual Copy
Using rdbuf():
ifstream source(sourceFile, ios::binary);
ofstream dest(destFile, ios::binary);
dest << source.rdbuf();
What happens here:
Binary Mode:
Verifying Copy
Comparing File Sizes:
if (file_size(sourceFile) == file_size(destFile)) {
cout << "Copy verified!" << endl;
}
What happens here:
When to Use Each Method
filesystem::copy_file():
Manual Copy:
Important Considerations
File Modes:
Error Handling:
File Overwriting:
return 0;
return 0; closes main and tells the operating system the program finished without an error.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What happens if data_copy.txt already exists?
Pick an answer to check it.
Question 2
What does dest << source.rdbuf() do?
Pick an answer to check it.
Questions people ask
How do I overwrite?
copy_file(src, dst, copy_options::overwrite_existing);
How do I copy a folder?
filesystem::copy(src, dst, copy_options::recursive);
Why binary mode for the manual copy?
So the bytes are copied exactly, with no newline conversion on Windows.