Copy File

Copying a File in C++

IntermediateTopic: File Handling Programs
Back

C++ Copy File Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#include <iostream>
#include <fstream>
#include <filesystem>
using namespace std;
using namespace filesystem;

int main() {
    string sourceFile = "data.txt";
    string destFile = "data_copy.txt";
    
    // Method 1: Using filesystem (C++17) - Simple
    try {
        copy_file(sourceFile, destFile);
        cout << "File copied successfully using filesystem!" << endl;
    } catch (const filesystem_error& e) {
        cout << "Error: " << e.what() << endl;
    }
    
    // Method 2: Manual copy - Read and write
    ifstream source(sourceFile, ios::binary);
    ofstream dest(destFile + "_manual", ios::binary);
    
    if (source.is_open() && dest.is_open()) {
        dest << source.rdbuf();  // Copy entire file buffer
        
        source.close();
        dest.close();
        
        cout << "File copied manually!" << endl;
    } else {
        cout << "Error opening files for manual copy." << endl;
    }
    
    // Verify copy
    if (exists(destFile)) {
        cout << "\nVerification:" << endl;
        cout << "Source size: " << file_size(sourceFile) << " bytes" << endl;
        cout << "Copy size: " << file_size(destFile) << " bytes" << endl;
        
        if (file_size(sourceFile) == file_size(destFile)) {
            cout << "File sizes match - Copy verified!" << endl;
        }
    }
    
    return 0;
}
Output
File copied successfully using filesystem!
File copied manually!

Verification:
Source size: 156 bytes
Copy size: 156 bytes
File sizes match - Copy verified!

Understanding Copy File

This program teaches you how to Copy a File in C++. File copying duplicates a source file to a destination file, preserving all content. Multiple methods are available, with the filesystem library (C++17) providing the simplest approach.

---

1. What This Program Does

The program demonstrates file copying:

Method 1: Using filesystem::copy_file() (C++17)
Method 2: Manual copy using read/write
Using rdbuf() for efficient buffer copying
Verifying copy by comparing file sizes

File copying enables backup, duplication, and file management.

---

2. Header Files Used

1.#include <iostream>
Provides cout and cin for input/output operations.
2.#include <fstream>
Provides file stream classes (ifstream, ofstream).
3.#include <filesystem>
Provides filesystem operations (C++17).

---

3. 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

---

4. Method 1: Using filesystem::copy_file()

Simple Copy

:

copy_file(sourceFile, destFile);

How it works

:

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;

5. Method 2: Manual Copy

Using rdbuf()

:

ifstream source(sourceFile, ios: :binary);
ofstream dest(destFile, ios: :binary);

dest << source.rdbuf();

How it works

:

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

---

6. Verifying Copy

Comparing File Sizes

:

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

}

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

How it works

:

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

---

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

---

8. 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

---

9. return 0;

This ends the program successfully.

---

Summary

File copying: duplicate source file to destination, preserve all content.
Method 1: filesystem::copy_file() (C++17) - simplest, one-line copy.
Method 2: Manual copy using rdbuf() - efficient buffer copy.
Use ios::binary mode for exact byte copy, preserves all data.
Verify copy by comparing file sizes or contents.
Understanding file copying enables backup and file management.
Essential for duplicating files, creating backups, and file operations.

This program is fundamental for learning file management, understanding file duplication, and preparing for backup and file handling operations in C++ programs.

Let us now understand every line and the components of the above program.

Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

Practical Learning Notes for Copy File

This C++ program is part of the "File Handling Programs" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.

A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.

For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.

Table of Contents