1
votes

I am writing a program to generate a bitmap image. When I was testing it, I found that C++ was writing extra bytes (at seemingly random locations) thus offsetting all of my bytes (subsequently messing up the image). I write to the file from an array. I cout the complete contents of the array, and they are perfect, however the extra bytes are always written. This was fixed by opening the file with the ios::binary flag.

Why would opening the file with and without the ios::binary flag matter if I am outputting from the exact same array.

Using Code::Blocks 12.11, default compiler with C++0X

1
Did you look at the bytes of the array content? For example, your text-outut-stream may well translate CR into CR/LF. My question would be "Why would I try to write binary data to a text output stream and expect it to work ? - WhozCraig
The answer given by Inspired matches my scenario perfectly.. and I look at the individual bytes (made my own buffer) as they go to ofstream. - ithenoob
Excellent. Its not an uncommon hiccup. Glad you found the answer. - WhozCraig

1 Answers

4
votes

Because you are most probably using Windows, and there are some conventions about how some special characters (e.g. new-line) are represented in text files: e.g. \n in Windows is converted into \r\n, and reading 0x1E ("EOF") raises end-of-file flag. These conversions do not occur if you open the file in binary (non-text) mode.

And even if you don't use Windows: always use binary mode for binary data, it's the portable way.