简体   繁体   English

无论如何,当输出可以是非 ASCII 时,为什么要使用 fopen() 模式 'b' (stdio.h)?

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

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" .使用 C 标准库stdio.h ,我读到它来输出 ASCII/文本数据,应该使用模式"w"并输出二进制数据,应该使用"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.如果我在 ASCII 模式下输出一个非 ASCII 字节,程序仍然输出正确的字节。

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.一些操作系统——大多被命名为“windows”——不保证它们会完全按照你传入的方式读取和写入文件。所以在windows上,它们实际上将\\r\\n映射到\\n。 This is fine and transparent when reading and writing ascii.这在读写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.基本上,如果您希望它按照您传入的方式忠实地读取和写入数据到文件中,那么总是给 Windows 'b' 标志。

There are certain transformations that can take place when outputting in ASCII (eg outputting neline+carriage-return when the outputted character is new-line) -- depending on your platform.以 ASCII 输出时可能会发生某些转换(例如,当输出的字符为换行符时输出 neline+carriage-return)——这取决于您的平台。 Such transformations will not take place when using binary format使用二进制格式时不会发生此类转换

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM