关于C#:fopen中r和rb有什么区别

what's the differences between r and rb in fopen

我尝试在C中使用fopen,第二个参数是打开模式。 两种模式" r"和" rb"往往使我感到困惑。 看来他们是一样的。 但有时最好使用" rb"。 那么,为什么" r"存在?
向我详细说明或举例说明。
谢谢。


您应该使用"r"来打开文本文件。不同的操作系统存储文本的方式略有不同,这将执行正确的翻译,因此您无需了解本地操作系统的特质。例如,您将知道换行符将始终显示为简单的"\
"
,而不管代码在哪里运行。

如果要打开非文本文件,则应使用"rb",因为在这种情况下,翻译不合适。


在Linux和通常的Unix上,"r""rb"相同。更具体地说,在文本模式和二进制模式下通过对文件进行fopen()赋值的FILE指针在Unixes上的行为相同。在Windows上,通常,在使用多个字符表示"换行符"的系统上,以文本模式打开的文件的行为就好像所有这些字符都是一个字符,即'\
'

如果要在任何系统上可移植地读取/写入文本文件,请使用"r"fopen()中的"w"。这样可以保证文件被正确地读写。如果要打开二进制文件,请使用"rb""wb",这样不幸的换行符翻译不会弄乱您的数据。

请注意,底层系统为您执行换行翻译的结果是,您无法确定可以使用fseek(file,0,SEEK_END)从文件读取的字节数。

最后,请参见文本和二进制I / O有什么区别?关于comp.lang.c常见问题解答。


使用" rb"打开一个二进制文件。那么当您读取文件的字节时,它们将不会被编码


  • " r"与" rt"在翻译模式下相同
  • " rb"是
    非翻译模式。

至少在Windows上这有所作为。有关详情,请参见该链接。


在大多数POSIX系统上,它将被忽略。但是,请检查系统以确保。

XNU

The mode string can also include the letter 'b' either as last character or as a character between the characters in any of the two-character strings described above. This is strictly for compatibility with ISO/IEC 9899:1990 ('ISO C90') and has no effect; the 'b' is ignored.

的Linux

The mode string can also include the letter 'b' either as a last
character or as a character between the characters in any of the two-
character strings described above. This is strictly for
compatibility with C89 and has no effect; the 'b' is ignored on all
POSIX conforming systems, including Linux. (Other systems may treat
text files and binary files differently, and adding the 'b' may be a
good idea if you do I/O to a binary file and expect that your program
may be ported to non-UNIX environments.)