4

With the C standard library stdio.h, I read that to output ASCII/text data, one should use mode "w" and to output binary data, one should use "wb". But why the difference?

In either case, I'm just outputting a byte (char) array, right? And if I output a non-ASCII byte in ASCII mode, the program still outputs the correct byte.

  • 8
    Automatic newline transformation. Barf. – Carl Norum Jun 21 '12 at 15:24
  • 1
    wiki.answers.com/Q/… – m0skit0 Jun 21 '12 at 15:25
  • 2
    Unless your goal is to make files that show up correctly in ancient versions of Windows Notepad, you should always use the "b" option. Text mode being different from binary mode just makes your life hell. If you need to support legacy text files with CR's, just strip the CR in your parser; if you're using scanf, it will ignore it for you as part of whitespace skipping. – R.. GitHub STOP HELPING ICE Jun 21 '12 at 15:31
  • Excellent comments. +1's all around. – JellicleCat Jun 21 '12 at 17:09
7

Some operating systems - mostly named "windows" - don't guarantee that they will read and write ascii to files exactly the way you pass it in. So on windows they actually map \r\n to \n. This is fine and transparent when reading and writing ascii. But it would trash a stream of binary data. Basically just always give windows the 'b' flag if you want it to faithfully read and write data to files exactly the way you passed it in.

| improve this answer | |
0

There are certain transformations that can take place when outputting in ASCII (e.g. outputting neline+carriage-return when the outputted character is new-line) -- depending on your platform. Such transformations will not take place when using binary format

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.