简体   繁体   中英

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM