Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

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.

IntermediateFile Handling ProgramsExample 6 of 6
copy-file.cpp
1#include <iostream>
2#include <fstream>
3#include <filesystem>
4using namespace std;
5using namespace filesystem;
6
7int main() {
8 string sourceFile = "data.txt";
9 string destFile = "data_copy.txt";
10
11 // Method 1: Using filesystem (C++17) - Simple
12 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 }
18
19 // Method 2: Manual copy - Read and write
20 ifstream source(sourceFile, ios::binary);
21 ofstream dest(destFile + "_manual", ios::binary);
22
23 if (source.is_open() && dest.is_open()) {
24 dest << source.rdbuf(); // Copy entire file buffer
25
26 source.close();
27 dest.close();
28
29 cout << "File copied manually!" << endl;
30 } else {
31 cout << "Error opening files for manual copy." << endl;
32 }
33
34 // Verify copy
35 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;
39
40 if (file_size(sourceFile) == file_size(destFile)) {
41 cout << "File sizes match - Copy verified!" << endl;
42 }
43 }
44
45 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. 1

    Try copy_file(data.txt, data_copy.txt) and catch filesystem_error.

  2. 2

    Open source and data_copy.txt_manual in binary mode.

  3. 3

    dest << source.rdbuf() copies everything.

  4. 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:

Duplicate source file to destination
Preserve all content exactly
Create new file with same data
Essential for backup and management

Copy Methods:

filesystem::copy_file(): simple, C++17
Manual read/write: more control
rdbuf(): efficient buffer copy
Binary mode for exact copy

Method 1: Using filesystem::copy_file()

Simple Copy:

copy_file(sourceFile, destFile);

What happens here:

One-line file copy
Handles all details automatically
Exception on error
C++17 required

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:

rdbuf(): copies entire file buffer
Efficient one-operation copy
Works with binary mode
Preserves exact content

Binary Mode:

ios::binary: exact byte copy
No text conversion
Preserves all data
Recommended for exact copy

Verifying Copy

Comparing File Sizes:

if (file_size(sourceFile) == file_size(destFile)) {

cout << "Copy verified!" << endl;

}

What happens here:

Compare source and destination sizes
Same size indicates successful copy
Can also compare contents
Verifies copy operation

When to Use Each Method

filesystem::copy_file():

C++17 available
Simple one-line copy
Automatic error handling
Recommended for new code

Manual Copy:

More control needed
Older C++ standards
Custom copy logic
Binary file handling

Important Considerations

File Modes:

Use ios::binary for exact copy
Preserves all data types
No text conversion issues
Essential for binary files

Error Handling:

Check if source exists
Handle write permissions
Verify destination writable
Provide user feedback

File Overwriting:

Destination may be overwritten
Check if destination exists
Ask user confirmation if needed
Handle overwrite carefully

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.