Hi, i tried fopen in C, the second parameter is open mode. two modes "r" and "rb" tricks me a lot...it seems they r the same...sometimes it better to use "rb", so, why does "r" exist?? can expain it to me, more detailed or examples thanx
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.
use "rb" to open a binary file. Then the bytes of the file won't be encoded when you read them
- "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.
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.