Search code examples
c++ifstreamofstream

Writing bytes to a file


I have an array of bytes defined as :

unsigned char * pixels = new unsigned char[pixelsLen];

and I want write all bytes from this array to a .bmp file.

This is how it does not work:

ifstream screen ( "input.bmp", ios::binary | ios::in );
ofstream output ( "output.bmp", ios::binary | ios::out | ios::app );
output.write( ( char * )&pixels, pixelsLen );
output.close();

This is how it does work :

ifstream screen ( "input.bmp", ios::binary | ios::in );
ofstream output ( "output.bmp", ios::binary | ios::out | ios::app );
for ( size_t i = 0; i < pixelsLen; i++ ) {
    output.write( ( char * )&pixels[i], 1 );
}
output.close();

The question is why it works when I'm writing it byte by byte and does not work when I'm trying to write it at once ?


Solution

  • Actually &pixels returns a pointer to pointer but std::ostream::write function gets pointer. So try this:

    ifstream screen ( "input.bmp", ios::binary | ios::in );
    ofstream output ( "output.bmp", ios::binary | ios::out | ios::app );
    output.write( reinterpret_cast<char *>(pixels), pixelsLen );
    output.close();
    

    Also try to avoid C-style casting.