Problem
I tried using fopen in C; the open mode is the second option. The two modes “r” and “rb” frequently perplex me. They appear to be the same. However, there are occasions when “rb” is preferable. So, what is the purpose of the letter “r”? Give me a detailed explanation or examples. Thank you very much.
Asked by Shaobo Wang
Solution #1
When opening text files, the command “r” should be used. Different operating systems store text in somewhat different ways, and this will handle the translations correctly so you don’t have to worry about the local operating system’s quirks. For example, regardless of where the code runs, newlines will always be represented by a plain “n.”
If you’re opening a file that isn’t text, you should use “rb,” because the translations aren’t applicable in this scenario.
Answered by caf
Solution #2
“r” and “rb” are the same on Linux and Unix in general. On Unixes, a FILE pointer obtained by fopen()ing a file in text mode and a FILE pointer obtained by fopen()ing a file in binary mode functions the same way. A file opened in text mode on Windows, and in general on systems that employ more than one character to denote “newlines,” behaves as if all those characters are just one character, ‘n’.
Use the “r” and “w” options in fopen to read/write text files on any OS (). This ensures that the files are correctly written and read. If you’re opening a binary file, use “rb” and “wb” to avoid having your data messed up by an accidental newline translation.
You can’t determine the number of bytes you can read from a file using fseek(file, 0, SEEK END) since the underlying system does the newline translation for you.
Finally, check What’s the Difference Between Text and Binary I/O? for more information. FAQs on comp.lang.c
Answered by Alok Singhal
Solution #3
To open a binary file, use “rb”. When you read the bytes of the file, they will not be encoded.
Answered by sagie
Solution #4
On Windows, at least, this makes a difference. Details can be found at that link.
Answered by Alex Budovski
Solution #5
It is ignored on most POSIX systems. However, double-check your system to make sure.
XNU
Linux
Answered by nathansizemore
Post is based on https://stackoverflow.com/questions/2174889/whats-the-differences-between-r-and-rb-in-fopen