0

I am trying to copy some binary source file to a target file. This seems to be the most popular way to do it.

Here it is in a simple test application:

#include "stdafx.h"
#include <fstream>

int main(int argc, const char* argv[])
{
    using namespace std;
    string sourceFile(argv[1]);
    string targetFile(argv[2]);

    ifstream src(sourceFile);
    ofstream dst(targetFile);

    dst << src.rdbuf();

    return 0;
}

If I build and run this example in Visual Studio 2010, only the first 522 bytes of the file are copied. Why is this so? And how can I extend this example to ensure all bytes are copied?

Community
  • 1
  • 1
elSnape
  • 302
  • 1
  • 12
  • 2
    What' sthe value of the 523rd byte? Add the `std::ios::binary` flag to the constructors. – Kerrek SB Jul 05 '13 at 11:55
  • Won't the rdbuf just buffer up some of the file? – doctorlove Jul 05 '13 at 11:58
  • If you know this is going to be running on Windows anyway, why not just use the built-in [`CopyFile`](http://msdn.microsoft.com/en-us/library/windows/desktop/aa363851.aspx) function and be done with it? – Jerry Coffin Jul 05 '13 at 12:01
  • Last byte was '18'. Adding the ios::binary flag solved the problem. Makes sense now, thanks. – elSnape Jul 05 '13 at 12:01
  • @JerryCoffin this is taken from cross platform code. `CopyFile` seems to be the quickest solution if it were Windows only. – elSnape Jul 05 '13 at 12:03
  • 2
    `std::ios::binary` is definitely not the default file mode. Windows treats a `CTRL-Z` in a text input stream as an EOF where your Mac obviously doesn't. – Blastfurnace Jul 05 '13 at 12:15

0 Answers0