C++ ofstream output to image file writes different data on Windows

c++, image, ofstream, windows-7

Solution

You must open the file in binary mode:

std::ofstream f("image.jpeg", std::ios::out | std::ios::binary);
//                                            ^^^^^^^^^^^^^^^^

Problem

Im doing a simple thing: writing the data of an image file stored as a string into the image file containing that string. ``` std::ofstream f("image.jpeg"); f << image_data; // image_data was created using python and copied over, in hex and turned back into ascii ``` And yet, the unexpected happens: becomes: I cannot understand why this is happening. When I use python2.7 to get the data from the original picture and write it to a new file, it works fine. When I compile and run my program in ubuntu, the picture comes out fine. When I write a large text file (larger than the image) into a .txt, the file comes out fine. It is only jpegs on Windows that fails. The original image I tried was an image from a PGP key packet, which came out with half of the person's head clear and the other half messed up. The compiled program doesnt mess up all of the data, since like I said above, some of the original picture is shown. Also, the images are the same size, so the jpeg format was preserved at least. What is happening? I am using ming2 4.7.2 in Code::Blocks on Windows 7. Is Windows just being crazy?

Original source