home *** CD-ROM | disk | FTP | other *** search
/ C by Discovery (4th Edition) / C_By_Discovery_4th_Edition.tar / C_By_Discovery_4th_Edition / _DISK_ / ch10 / nl.c < prev    next >
C/C++ Source or Header  |  2005-06-16  |  1KB  |  39 lines

  1. /*               nl.c
  2.  *
  3.  *   Synopsis  - Opens a text file and copies the lines of the
  4.  *               file to standard output with each text line
  5.  *               preceded by a line number.
  6.  *
  7.  *   Objective - To illustrate the use of fgets() for input and
  8.  *               fputs() for output.
  9.  */
  10.  
  11. /* Include Files */
  12. #include <stdio.h>
  13. #include <stdlib.h>
  14.  
  15. /* Constant Declarations */
  16. #define NUMCHARS 512
  17.  
  18. int main( int argc, char *argv[] )
  19. {
  20.      char inarray[NUMCHARS];                               /* Note 1 */
  21.      int linecount = 1;
  22.      FILE *fp;
  23.  
  24.      if ( argc < 2 ) {
  25.           printf( "Usage:  nl  filename\n" );
  26.           exit( 1 );
  27.      }
  28.      else if (( fp = fopen( argv[1], "r" )) == NULL ) {
  29.           printf( "Unable to open file %s.\n", argv[1] );
  30.           exit( 1 );
  31.      }
  32.                                                            /* Note 2 */
  33.      while ( fgets( inarray, NUMCHARS, fp ) != NULL ) {
  34.           printf( "%d\t", linecount++ );
  35.           fputs( inarray, stdout );                        /* Note 3 */
  36.      }
  37.      fclose( fp );
  38.      return 0;
  39. }