Text Files VS Binary Files in C Language

Files can be associated in two different categories. These are

  1. Text Files
  2. Binary Files

This classification arises out of the mode in which a file is opened. If we open a file in text mode, “r” or “rt” is to be specified as a mode in fopen() function and if in binary mode, “rb” is to be specified as a mode. The Text and Binary files are different in three areas:

  1. Handling a newlines
  2. Representation of end of file
  3. Storage of numbers

1. Handling of newlines

In text mode, a newline is converted into carriage return and linefeed combination before being written to the disk and again converted into newline when read from disk. It will count two characters instead of one in text mode i.e. one for carriage return and other for line feed.

In binary mode the conversion does not happen. Thus in case of binary mode, only one character is counted for newline.

C Interview Question-Answers

Representation of end of File

The second difference between text and binary mode is in the way the end of file is detected. In text mode a special character is inserted after the last character whose ASCII value is 26.

If this character is detected at any point in the file, the read function will return EOF signal. In binary mode, there is no such special character present in the binary mode files to mark the end of file.

These Files checks for the end of file by counting the number of characters present in the directory entry of the file.

3. Storage of Numbers

In text mode, the number of characters are stored as a character by character format i.e. for 2345 to be stored, 4 bytes are required, similarly for 2345.67 will take 7 bytes on disk. So the numbers with more digits would require more disk space.

In Binary mode, numbers can be stored by changing them into binary format. It means each number will occupy same numbers of bytes on disk as it occupies in memory. So storage of numbers in binary files is efficient.

fscanf() and fprintf() functions use text mode, whereas fread() and fwrite() functions use binary mode.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top