Wednesday, November 2, 2011

File Operations in C programming language

There are different operations that can be carried out on a file.
These are:
(a)  Creation of a new file
(b)  Opening an existing file
(c)  Reading from a file
(d)  Writing to a file
(e)  Moving to a specific location in a file (seeking)
(f)  Closing a file
Let us now write a program to read a file and display its contents
on the screen. We will first list the program and show what it does,
and then dissect it line by line. Here is the listing…

/* Display contents of a file on screen. */ 
# include "stdio.h"
main( )
{
      FILE  *fp ;
      char  ch ;
 
      fp = fopen ( "PR1.C", "r" ) ;

      while ( 1 )
 {
            ch = fgetc ( fp ) ;

            if ( ch == EOF )
   break ;

            printf ( "%c", ch ) ;
 }

      fclose ( fp ) ;
}

On execution of this program it displays the contents of the file ‘PR1.C’ on the screen. Let us now understand how it does the same.

No comments:

Post a Comment