Copy File
Copying a File in C++
IntermediateTopic: File Handling Programs
C++ Copy File Program
This program helps you to learn the fundamental structure and syntax of C++ programming.
#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
File copying can be done: 1) Using filesystem::copy_file() (C++17) - simplest, 2) Manual method - read from source, write to destination. Use rdbuf() to copy entire file buffer efficiently. For binary files, use ios::binary mode. Always verify the copy by comparing file sizes or contents.
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.