Why does the C ++ ofstream write () method change my source data?

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

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

but the image doesnโ€™t work out right, it looks distorted by random black and white stripes everywhere. After comparing the image with the original in hex view, I found out that thestream changes the data when it thinks I'm writing a newline character. In any case, when 0x0A is displayed in the original, thestream writes as two bytes: 0x0D0A. I have to assume that thestream intends to convert from LF to CRLF only, is there a standard way to make it not do this?

+6
c ++ file-io visual-studio
source share
5 answers

Set the mode to binary when opening the file:

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

+9
source share

You must set the mode of the binary file when you open it:

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

Thus, the stream does not attempt to customize newlines in its own text format.

+9
source share

Try opening a stream from a binary file. Something like this should work:

 ofstream ofs; ofs.open(filename, ios::out | ios::binary); ofs.write(buffer, bufferLen); ofs.close(); 
+5
source share

Since you do not open the file in binary mode, by default it is set to the format. In formatted output, your implementation converts end-of-line characters as you describe.

+1
source share

I would like my version to write nothing at all ... no errors, no complaints, nothing bad when debugging it, but it doesnโ€™t even try to create a file. What the hell was wrong with fopen, fwrite and fclose ... I never had a problem with them.

-2
source share

All Articles