Text Files and Binary Files in C

Text Files

All the programs that we wrote in this chapter so far worked on text files. Some of them would not work correctly on binary files. A text file contains only textual information like alphabets, digits and special symbols. In actuality the ASCII codes of these characters are stored in text files. A good example of a text file is any C program, say PR1.C.

Binary Files

Binary file is merely a collection of bytes. This collection might be a compiled version of a C program (say PR1.EXE), or music data stored in a wave file or a picture stored in a graphic file. A very easy way to find out whether a file is a text file or a binary file is to open that file in Turbo C/C++. If on opening the file you can make out what is displayed then it is a text file, otherwise it is a binary file.

Example of Text Files and Binary Files in C

#include "stdio.h" 
main( ) 
 FILE *fs, *ft ; 
 int ch ; 
 fs = fopen ( "pr1.exe", "rb" ) ; 
 if ( fs == NULL ) 
 puts ( "Cannot open source file" ) ; 
 exit( ) ; 
 ft = fopen ( "newpr1.exe", "wb" ) ; 

if ( ft == NULL ) 
 puts ( "Cannot open target file" ) ; 
 fclose ( fs ) ; 
 exit( ) ; 
 while ( 1 ) 
 ch = fgetc ( fs ) ; 
 if ( ch == EOF ) 
 break ; 
 fputc ( ch, ft ) ; 
 fclose ( fs ) ; 
 fclose ( ft ) ; 

Using this program we can comfortably copy text as well as binary files. Note that here we have opened the source and target files in “rb” and “wb” modes respectively. While opening the file in text mode we can use either “r” or “rt”, but since text mode is the default mode we usually drop the ‘t’.

From the programming angle there are three main areas where text and binary mode files are different. These are:

  • Handling of newlines
  • Representation of end of file
  • Storage of numbers

Leave a Comment