What are the differences between r and rb in fopen

I tried using fopen in C, the second parameter is open mode. Two modes "r" and "rb" scare me very much. They seem to be the same. But sometimes it is better to use "rb". So why does r exist? Explain this to me in detail or with examples. Thank.

+43
c linux windows file
Feb 01 2018-10-01T00
source share
5 answers

You can use "r" to open text files. Different operating systems have slightly different ways of storing text, and this will perform the correct translations, so you do not need to know about the features of the local operating system. For example, you will learn that newlines will always be displayed as simple "\n" , no matter where the code is executed.

You should use "rb" if you open non-text files, because in this case translations are not suitable.

+57
01 feb. 2018-10-02T00
source share

On Linux and Unix, in general, "r" and "rb" same. More specifically, the FILE pointer obtained by fopen() with a file in text mode and binary mode behaves the same on Unix. In windows, and in general in systems that use more than one character to represent " newlines ", a file opened in text mode behaves as if all these characters are just one character, '\n' .

If you want to read / write text files portable on any system, use the "r" and "w" in fopen() . This ensures that the files are written and read correctly. If you open the binary, use "rb" and "wb" , so a bad newline will not spoil your data.

Please note that the consequence of the basic newline system is that you cannot determine the number of bytes that you can read from a file using fseek (file, 0, SEEK_END) .

Finally, see What is the difference between text and binary I / O? at comp.lang.c Frequently Asked Questions .

+22
Feb 01 '10 at 5:57
source share

use "rb" to open the binary. Then the bytes of the file will not be encoded when they are read.

+6
Feb 01 '10 at 5:50
source share

It matters to Windows, at least. See this link for more details.

+6
Feb 01 '10 at 5:53
source share

On most POSIX systems, it is ignored. But check your system.

XNU

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

Linux

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

+1
Jan 12 '17 at 16:09 on
source share



All Articles