Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use fopen() mode 'b' (stdio.h) when output can be non-ASCII regardless?

Tags:

c

stdio

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.

like image 968
JellicleCat Avatar asked Feb 21 '23 02:02

JellicleCat


1 Answers

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.

like image 144
Rafael Baptista Avatar answered May 01 '23 15:05

Rafael Baptista