1

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

3
  • 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 ? Commented Aug 29, 2013 at 20:15
  • 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. Commented Aug 29, 2013 at 20:20
  • Excellent. Its not an uncommon hiccup. Glad you found the answer. Commented Aug 29, 2013 at 20:27

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.