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

  1. /* PAGER.C illustrates line input and output on stream text files.
  2.  * Functions illustrated include:
  3.  *      fopen           fclose          fcloseall       feof
  4.  *      fgets           fputs           rename
  5.  */
  6.  
  7. #include <stdio.h>
  8. #include <io.h>
  9. #include <dos.h>
  10. #include <stdlib.h>
  11. #include <string.h>
  12.  
  13. #define MAXSTRING 128
  14. #define PAGESIZE 55
  15. enum BOOL { FALSE, TRUE };
  16.  
  17. void quit( int error );
  18. FILE *infile, *outfile;
  19. char outpath[] = "tmXXXXXX";
  20.  
  21. main( int argc, char *argv[] )
  22. {
  23.     char tmp[MAXSTRING];
  24.     long line = 0, page = 1;
  25.     int  endflag = FALSE;
  26.  
  27.     /* Open file (from command line) and output (temporary) files. */
  28.     if( (infile = fopen( argv[1], "rt" )) == NULL )
  29.         quit( 1 );
  30.     mktemp( outpath );
  31.     if( (outfile = fopen( outpath, "wt" )) == NULL )
  32.         quit( 2 );
  33.  
  34.     /* Get each line from input and write to output. */
  35.     while( 1 )
  36.     {
  37.         /* Insert form feed and page header at the top of each page. */
  38.         if( !(line++ % PAGESIZE) )
  39.             fprintf( outfile, "\f\nPage %d\n\n", page++ );
  40.  
  41.         if( fgets( tmp, MAXSTRING - 1, infile ) == NULL )
  42.             if( feof( infile ) )
  43.                 break;
  44.             else
  45.                 quit( 3 );
  46.         if( fputs( tmp, outfile ) == EOF )
  47.             quit( 3 );
  48.     }
  49.  
  50.     /* Close files and move temporary file to original by deleting
  51.      * original and renaming temporary.
  52.      */
  53.     fcloseall();
  54.     remove( argv[1] );
  55.     rename( outpath, argv[1] );
  56.     exit( 0 );
  57. }
  58.  
  59. /* Handle errors. */
  60. void quit( int error )
  61. {
  62.     switch( error )
  63.     {
  64.         case 1:
  65.             perror( "Can't open input file" );
  66.             break;
  67.         case 2:
  68.             perror( "Can't open output file" );
  69.             fclose( infile );
  70.             break;
  71.         case 3:
  72.             perror( "Error processing file" );
  73.             fclose( infile );
  74.             fclose( outfile );
  75.             remove( outpath );
  76.             break;
  77.     }
  78.     exit( error );
  79. }
  80.