home *** CD-ROM | disk | FTP | other *** search
/ Microsoft Programmer's Library 1.3 / Microsoft-Programers-Library-v1.3.iso / sampcode / c / other / file / table.c < prev    next >
Encoding:
C/C++ Source or Header  |  1988-11-01  |  1.3 KB  |  50 lines

  1. /* TABLE.C illustrates reading and writing formatted file data using
  2.  * functions:
  3.  *      fprintf         fscanf
  4.  */
  5.  
  6. #include <stdio.h>
  7. #include <io.h>
  8. #include <fcntl.h>
  9. #include <sys\types.h>
  10. #include <sys\stat.h>
  11. #include <stdlib.h>
  12.  
  13. main()
  14. {
  15.     char buf[128];
  16.     FILE *ftable;
  17.     long l, tl;
  18.     float fp, tfp;
  19.     int  i, c = 'A';
  20.  
  21.     /* Open an existing file for reading. Fail if file doesn't exist. */
  22.     if( (ftable = fopen( "table.smp", "r")) != NULL )
  23.     {
  24.         /* Read data from file and total it. */
  25.         for( i = 0, tl = 0, tfp = 0.0; i < 10; i++ )
  26.         {
  27.             fscanf( ftable, "\t%s %c: %ld %f\n", buf, &c, &l, &fp );
  28.             tl += l;
  29.             tfp += fp;
  30.             printf( "\t%s %c: %7ld %9.2f\n", buf, c, l, fp );
  31.         }
  32.         printf( "\n\tTotal:  %7ld %9.2f\n", tl, tfp );
  33.     }
  34.     else
  35.     {
  36.         /* File did not exist. Create it for writing. */
  37.         if( (ftable = fopen( "table.smp", "w" )) == NULL )
  38.             exit( 1 );
  39.  
  40.         /* Write table to file. */
  41.         for( i = 0, l = 99999, fp = 3.14; i < 10; i++ )
  42.             fprintf( ftable, "\tLine %c: %7ld %9.2f\n",
  43.                      c++, l /= 2, fp *= 2 );
  44.  
  45.         printf( "Created table file. Run again to read it.\n" );
  46.     }
  47.     fclose( ftable );
  48.     exit( 0 );
  49. }
  50.