what's the differences between r and rb in fopen
I tried using fopen in C, the second parameter is the open mode. The two modes "r" and "rb" tend to confuse me a lot. It seems they are the same. But sometimes it is better to use "rb". So, why does "r" exist? Explain it to me in detail or with examples. Thank You.
Solution 1:
You should use "r"
for opening text files. Different operating systems have slightly different ways of storing text, and this will perform the correct translations so that you don't need to know about the idiosyncracies of the local operating system. For example, you will know that newlines will always appear as a simple "\n"
, regardless of where the code runs.
You should use "rb"
if you're opening non-text files, because in this case, the translations are not appropriate.
Solution 2:
On Linux, and Unix in general, "r"
and "rb"
are the same. More specifically, a FILE
pointer obtained by fopen()
ing a file in in text mode and in binary mode behaves the same way on Unixes. On windows, and in general, on systems that use more than one character to represent "newlines", a file opened in text mode behaves as if all those characters are just one character, '\n'
.
If you want to portably read/write text files on any system, use "r"
, and "w"
in fopen()
. That will guarantee that the files are written and read properly. If you are opening a binary file, use "rb"
and "wb"
, so that an unfortunate newline-translation doesn't mess your data.
Note that a consequence of the underlying system doing the newline translation for you is that you can't determine the number of bytes you can read from a file using fseek(file, 0, SEEK_END).
Finally, see What's the difference between text and binary I/O? on comp.lang.c FAQs.
Solution 3:
use "rb" to open a binary file. Then the bytes of the file won't be encoded when you read them
Solution 4:
- "r" is the same as "rt" for Translated mode
- "rb" is non-translated mode.
This makes a difference on Windows, at least. See that link for details.
Solution 5:
On most POSIX systems, it is ignored. But, check your system to be sure.
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.)