Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 270
Graphics Noob Avatar asked Aug 29 '09 02:08

Graphics Noob


People also ask

Does ofstream append to file?

In order for us to append to a file, we must put the ofstream() function in append mode, which we explain in the next paragraph. With the full line, ofstream writer("file1. txt", ios::app);, we now create a connection to open up the file1. txt file in order to append contents to the file.

What does ofstream stand for?

ostream is a general purpose output stream. cout and cerr are both examples of ostreams. ifstream is an input file stream. It is a special kind of an istream that reads in data from a data file. ofstream is an output file stream.


2 Answers

Set the mode to binary when you open the file:

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

like image 185
Owen Avatar answered Oct 15 '22 19:10

Owen


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.

like image 35
sth Avatar answered Oct 15 '22 19:10

sth