Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) CopyFile

 

CopyFile is a file I/O code snippet to copy a file.

 

 

 

 

 

 

CopyFile using STL only

 

If the target file location already exists, this version will overwrite it.

 

#include <cassert>
#include <fstream>

//From http://www.richelbilderbeek.nl/CppCopyFile.htm
void CopyFile(const std::string& fileNameFrom, const std::string& fileNameTo)
{
  assert(FileExists(fileNameFrom));
  std::ifstream in (fileNameFrom.c_str());
  std::ofstream out(fileNameTo.c_str());
  out << in.rdbuf();
  out.close();
  in.close();
}

 

 

 

 

 

CopyFile using the Boost.Filesystem library

 

If the target file location already exists, this version will throw an exception.

 

#include <cassert>
#include <boost/filesystem.hpp>

//From http://www.richelbilderbeek.nl/CppCopyFile.htm
void CopyFile(const std::string& from, const std::string& to)
{
  assert(boost::filesystem::is_regular_file(from)
    && "Assume file is present");
  boost::filesystem::copy_file(from,to);
}

int main()
{
  CopyFile("main.o","did_it.txt");
}

 

 

 

 

 

CopyFile using the VCL library

 

For if you develop using C++ Builder.

 

#include <SysUtils.hpp> //VCL specific

//From http://www.richelbilderbeek.nl/CppCopyFile.htm
int main()
{
  //Will FileTo.txt be overwritten if it already exists? No.
  const bool failIfExists = true;
  CopyFile("FileFrom.txt","FileTo.txt",failIfExists);
}

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict