Home  >  Article  >  Backend Development  >  How to copy files using C++?

How to copy files using C++?

王林
王林Original
2024-06-05 14:44:01405browse

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 using C++?

#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:

  1. Contains the fstream header.
  2. Declare the copyFile function, where sourceFile is the source file path and targetFile is the target file path.
  3. Create new streams pointing to source and destination files.
  4. Check whether the stream is opened successfully.
  5. Allocate a buffer to read and write file data.
  6. Copy the file data block by block using the read and write methods on the stream.
  7. Close the stream to release system resources.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn