Operations on integer data

Program 61) A file named DATA contains a series of integer numbers. Code a program to read these number and then write all 'odd' numbers to a file to be called ODD and 'even' numbers to a file to be called EVEN.

This program uses three files simultaneously and therefore, we need to  define three-file pointers f1, f2 and f3.
First, the file DATA containing integer value is created. The integer values are read from the terminal and are written to the file DATA with the help of the statement
                      putw (number, f1) ;
Notice that when we type -1, the reading is terminated and the file is closed. The next step is to open all the  three files, DATA for reading, ODD and EVEN for writing. The contents of DATA file are read, integer by integer, by the function getw (f1) and written to ODD OR EVEN file an appropriate test. Note that the statement

                      (number = getw (f1))  ! = EOF
reads a value, assigns the same to number, and then tests for the end-of-life mark.
Finally, the program displays the contents of ODD and EVEN files. It is important to note that the files ODD and EVEN opened for writing are closed before they are reopened for reading.

                                         PROGRAM

#include <stdio.h>
main ( )
 {
    FILE  *f1, *f2, *f3 ;
    int number, i ;

    printf ("Contents of DATA file\n\n") ;
    f1 = fopen ("DATA", "w") ;   /*  Create DATA file   */
    for (i = 1; i <= 30; i++)
    {
        scanf ("%d", &number) ;
        if (number == - ) break ;
        putw (number, f1) ;
   }
   fclose (f1) ;

   f1 = fopen ("DATA", "r") ;
   f2 = fopen ("ODD", "w") ;
   f3 = fopen ("EVEN", "w") ;

 /*    Read from DATA file   */
 while ((number = getw (f1))  ! = EOF)
 {
      if (number %2 == 0)
         putw (number, f3) ;   /*   Write to EVEN file   */
      else
         putw (number, f2) ;   /*   Write to ODD file    */
 }
 fclose (f1) ;
 fclose (f2) ;
 fclose (f3) ;

 f2 = fopen ("ODD", "r") ;
 f3 = fopen ("EVEN", "r") ;

 printf ("\n\nContents of ODD file\n\n") ;
 while ((number = getw (f2))  ! = EOF)
      printf ("%4d", number) ;

 fclose (f2) ;
 fclose (f3) ;

 }

Output:       Contents od DATA file
                111 222 333 444 555 666 777 888 999 000 121
                   232 343 454 565 -1

                  Contents of ODD FILE
                111 333 555 777 121 343 365

                  Contents of EVEN file
                 222 444 666 868 0 232 454

No comments:

Post a Comment