Character oriented read/write operations on a file

Program 60) Write a program to read data from  the keyboard. Write it to file called INPUT, again read the same data from the INPUT file, and display it on the screen.

A program and the related input and output data, are shown below. We enter the input data via the keyboard and the program writes it, character by character, to teh file INPUT. The end of the data is indicated by entering an EOF character, which is control-Z in the reference system. (This may be control-D in other system.) The file INPUT is closed at this signal.

                                     PROGRAM

#include <stdio.h>

main ( )
 {
        FILE *f1 ;
        char c ;
        printf ("Data the file INPUT\n\n") ;
         /*   Open the file INPUT   */
        f1 = fopen ("INPUT", "w") ;

       /*   Get a character from keyboard   */
       while ((c=getchar ())  ! = EDF)
            
               /*      Write a character to INPUT   */
               put c (c, f1) ;

     /*  Close the file INPUT  */

     fclose (f1) ;
     printf ("\nData output\n\n") ;

      /*   Reopen the file INPUT   */
       f1 = fopen ("INPUT", "R") ;

     /*    Read a character from INPUT   */
      while ((c=getc (f1))  ! = EOF)

            /*   Display a charcater on screen   */
            printf ("%c", c) ;

     /*   Close the file INPUT    */
     fclose (f1) ;
 }

Output:      Data Input
                  This is a program to test the file handling
                  feature on this system^Z

                 Data Output
                 This is a program to test the file handling
                 feature on this system

The file INPUT is again responed for reading. The program then reads ite contents character by character, and displays it on the screen. Reading is terminated when getc encounters the end-of-file mark EOF.
Testing for the end-of-file condition is important. Any attempt to read past the end of file might either cause the program to terminate with an error or result in an ininite loop situation.     

No comments:

Post a Comment