cfileiotext-filesbinaryfiles

What are the consequences of opening a file in C in text or binary mode?


I was wondering if the mode (text or binary) that we use for opening a file in C really matters.

For example, in general, we use fread and fwrite for reading and writing in binary mode. Can we use those functions when we open a file in textual mode?

Besides that, in general, we can use fscanf and fprintf for reading and writing in textual mode. Can we use those functions if we open a file in binary mode?

What are the consequences of opening a file in textual or binary modes?


Solution

  • On POSIX-compliant operating systems (e.g. Linux, MacOS), there is no difference between binary mode and text mode.

    However, that is not the case on Microsoft Windows.

    Internally, text files on Microsoft Windows normally use \r\n (carriage return followed by line-feed) to terminate a line. If you open a text file in binary mode, you will therefore see \r\n at the end of every line (except maybe the last line). On the other hand, if you open a text file in text mode, the C runtime library will automatically translate all \r\n to \n.

    As a consequence of this translation, the effective file size (i.e. the number of times you can call fgetc until you reach the end of the file) is different depending on whether you use text mode or binary mode.

    Another consequence of this translation is that you cannot use the function fseek in text mode to jump a certain number of characters in the file. This is only possible in binary mode. The reason for this is that in text mode, the number of bytes between two file positions may be different than in binary mode.

    Another issue on Microsoft Windows is that in text mode, the byte value '\x1A' is interpreted as the end of the file. Therefore, if you open a binary file in text mode, then the file may appear a lot shorter than it actually is, if it happens to contain a byte with the value '\x1A'.

    You can use the functions fread, fwrite, fprintf and fscanf at will in both text mode and binary mode. But the formatted I/O functions fprintf and fscanf will generally be more useful with text files opened in text mode, whereas the unformatted I/O functions fread and fwrite will generally be more useful with binary files opened in binary mode.