Midas
Midas

Reputation: 7131

Why ofstream::rdbuf() is always empty?

ofstream ofs1("file1.dat", ios::out | ios::binary);

unsigned char data[64] = {0};
ofs1.write((char*) &data, sizeof(data));

if (some_condition)
{
    ofstream ofs2("file2.dat", ios::out | ios::binary);
    ofs2 << ofs1.rdbuf();// This does not work.
}

unsigned char more_data[32] = {1};
ofs1.write((char*) &more_data, sizeof(more_data));

As expected, file1.dat is 96 bytes in size after executing the code. However, file2.dat is 0 bytes, where I would expect it to be 64 bytes. Apparently ofstream::rdbuf() is always empty, or is it not supposed to be used like this?

Practical use for this: an application that writes several files using the same header (e.g. a colour palette). In this code example the contents of data (colour palette) are static, but it can obviously be replaced by a more complex computation, which would be overkill to repeat for each output file...

Upvotes: 0

Views: 1515

Answers (1)

user657267
user657267

Reputation: 21000

Your issue is that an ofstream by default opens its buffer in output mode only, and either way you're only passing std::ios_base::out, which means the buffer cannot be read from.

To fix this you will need to switch to using an fstream and open it with std::ios_base::in | std::ios_base::out | std::ios_base::binary.

You will also need to seek to the start of the file before calling rdbufby calling seekg(0, std::ios_base::beg).

Upvotes: 3

Related Questions