views:

633

answers:

4

I have a jpeg image in a char[] buffer in memory, all I need to do is write it out to disk exactly as is. Right now I'm doing this

ofstream ofs;
ofs.open(filename);
ofs.write(buffer, bufferLen);
ofs.close();

but the image doesn't come out right, it looks garbled with random black and white stripes everywhere. After comparing the image with the original in a hex viewer, I found out that the ofstream is modifying the data when it thinks I'm writing a newline character. Anyplace that 0x0A shows up in the original, the ofstream writes as two bytes: 0x0D0A. I have to assume the ofstream is intending to convert from LF only to CRLF, is there a standard way to get it to not do this?

+6  A: 

Set the mode to binary when you open the file:

http://www.cplusplus.com/reference/iostream/ofstream/ofstream/

Ow01
Thanks I knew it had to be something simple
Graphics Noob
+7  A: 

You should set the file mode to binary when you are opening it:

std::ofstream file;
file.open("filename.jpg", std::ios_base::out | std::ios_base::binary);

This way the stream doesn't try to adjust the newlines to your native text format.

sth
+4  A: 

Try opening the ofstream as binary. Something like this should work:

ofstream ofs;
ofs.open(filename, ios::out | ios::binary);
ofs.write(buffer, bufferLen);
ofs.close();
cjcela
A: 

Since you are not opening the file in binary mode, it is set to formatted output by default. In formatted output, your implementation performs conversion of the end-of-line characters as you describe.

Peter Jansson