6
votes

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?

5

5 Answers

9
votes
9
votes

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.

5
votes

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();
1
votes

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.

-2
votes

I wish I could get my version to write anything at all... no errors, no complaints, nothing wrong when you debug it but it doesn't even try and create the file. What the hell was wrong with fopen, fwrite and fclose... I never had a problem with them