1

Possible Duplicate:
Copy a file in an sane, safe and efficient way

I've searched for similar topics, but I couldn't find the answer for large binary files. Considering that I have very large binary files (like ~10 or ~100 GB each), how do I copy them with the following function, using standard C++ (no POSIX functions) :

bool copy(const std::string& oldName, const std::string& newName)
{
    /* SOMETHING */
}

EDIT : Is the following implementation ok ? (adapted from the link in comments)

bool copy(const std::string& oldName, const std::string& newName)
{
    bool ok = false;
    std::ifstream oldStream(oldName.c_str(), std::ios::binary);
    std::ofstream newStream(newName.c_str(), std::ios::binary);
    if (oldStream.is_open() && newStream.is_open()) {
        newStream << oldStream.rdbuf();
        ok = (oldStream.good() && newStream.good());
    }
    return ok;
}
Community
  • 1
  • 1
Vincent
  • 57,703
  • 61
  • 205
  • 388
  • Copy files means using the File System. Thus the **most efficient way** is to call the appropriate OS routines that interact with he File System. – Martin York Oct 08 '12 at 03:56
  • is the operator '<<' ok for binary files ? – Vincent Oct 08 '12 at 04:08
  • @Vincent, it should be when you're using `std::ios::binary`. Unfortunately, it's also very slow on many implementations. – Ben Voigt Oct 08 '12 at 04:11
  • 1
    @Vincent: If you mean is a file opened in std::ios::binary mode. Then yes. The mode it is opened in has little affect on its usage see(http://stackoverflow.com/questions/12766636/difference-in-using-read-write-when-stream-is-opened-with-without-iosbinary-mo/12766972#comment17265240_12766972) – Martin York Oct 08 '12 at 04:12

1 Answers1

2

You may use std::fopen, std::fread, std::fwrite, and std::fclose, all of which are part of the standard C++ library (#include <cstdio>, very portable) and won't mess up binary data as long as you don't use a "t" specifier to fopen.

It will even be reasonably quick if you pick an appropriate buffer size (say 1 mebibyte) that gets you into the realm of sequential I/O performance.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720