File Input/output In "C" Programming

Posted by Tushar Bedekar

The Standard I/O Library provides similar routines for file I/O to those used  for standard I/O.

The routine getc(fp) is similar to getchar()
and putc(c,fp) is similar to putchar(c).

Thus the statement

            c = getc(fp);

reads the next character from the file referenced by fp and the statement


writes the character c into file referenced by fp.

       Basic Program me:-

/* file.c: Display contents of a file on screen */

#include <stdio.h>

void main()
            FILE *fopen(), *fp;
            int c ;

            fp = fopen( “prog.c”, “r” );
            c = getc( fp ) ;                        
            while (  c != EOF )
                        putchar( c );              
                        c = getc ( fp );              

            fclose( fp );


In this program, we open the file prog.c for reading.

We then read a character from the file. This file must exist for this program to work.

If the file is empty, we are at the end, so getc returns EOF a special value to indicate that the end of file has been reached. (Normally -1 is used for EOF)

The while loop simply keeps reading characters from the file and displaying them, until the end of the file is reached.

The function fclose is used to close the file i.e. indicate that we are finished processing this file.

We could reuse the file pointer fp by opening another file.

This program is in effect a special purpose cat command. It displays file contents on the screen, but only for a file called prog.c.
back to top