Question

First, I'm interested in what is best way for working with big files, is this code at bottom recommended way ?

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    ifstream file("first.exe", ios::binary | ios::app);
    file.seekg(0, ios::end);
    int size = file.tellg();
    file.seekg(0, ios::beg);
    char content[size];
    file.read(content, size);
    ofstream file2("second.exe", ios::binary);
    file2.write(content, size);
    file2.close();
}

also, why is necessary to use binary mode in this case ?

Was it helpful?

Solution

Is it the recommended way? Not really. See below.

Binary mode?

There are two ways to open a file: Text mode and Binary mode. The default is Text mode, unless you use std::ios::binary when opening the file.

On Linux/Unix binary mode and text mode are identical. It makes no difference.

On Windows, when a file is opened in Text mode the o/s does some transformations. When you write a \n (ASCII 10) it gets converted to a \r\n pair (ASCII 10 and 13). When you read a \r\n pair, it gets converted to a single \n. Also Ctl-Z (ASCII 26) is treated as end of file so reading will terminate.

The reasons for this are historical and I won't go into detail now. If you read and write plain ASCII text, this causes no problems and can even be desirable. If you are working with anything else (e.g. an exe file) it is essential that you use binary mode.

The code below demonstrates a simple technique for file i/o that tries to capture the essence of C++ programming. I hope it is reasonably self-explanatory. Lookup reference for std::copy(), std::istreambuf_iterator and std::ostreambuf_iterator and ask questions if needed.

#include <iostream>
#include <fstream>
#include <algorithm>

int main() 
{
    std::ifstream fsIn("first.exe", std::ios::binary);
    std::ofstream fsOut("second.exe", std::ios::binary|std::ios::trunc);

    std::copy(std::istreambuf_iterator<char>(fsIn), 
              std::istreambuf_iterator<char>(), 
              std::ostreambuf_iterator<char>(fsOut));
    return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top