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?
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.
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.
Set the mode to binary when you open the file:
http://www.cplusplus.com/reference/iostream/ofstream/ofstream/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With