C++ – Why does the C++ ofstream write() method modify the raw data

cfile-iovisual studio

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?

Best Answer

Set the mode to binary when you open the file:

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