How to copy files in C++? Use std::ifstream and std::ofstream streams to read the source file, write to the destination file, and close the stream. 1. Create a new stream of source and destination files. 2. Check whether the stream is opened successfully. 3. Copy the file data block by block and close the stream to release resources.
#How to copy files in C++?
In C++, files can be copied using the std::ifstream
and std::ofstream
streams. This process consists of three main steps: reading the source file, writing to the destination file, and closing the stream.
Code example:
#include <fstream> void copyFile(const std::string& sourceFile, const std::string& targetFile) { std::ifstream inputFile(sourceFile, std::ios::binary); std::ofstream outputFile(targetFile, std::ios::binary); if (!inputFile.is_open()) { std::cerr << "Error: Unable to open source file." << std::endl; return; } if (!outputFile.is_open()) { std::cerr << "Error: Unable to open target file." << std::endl; return; } char buffer[1024]; while (inputFile.read(buffer, sizeof(buffer))) { outputFile.write(buffer, inputFile.gcount()); } inputFile.close(); outputFile.close(); }
Practical case:
To use this function to copy files, you can follow the steps below:
fstream
header. copyFile
function, where sourceFile
is the source file path and targetFile
is the target file path. read
and write
methods on the stream. The above is the detailed content of How to copy files using C++?. For more information, please follow other related articles on the PHP Chinese website!