Displays a listing with line numbers - C File

C examples for File:File Read

Description

Displays a listing with line numbers

Demo Code

#include <stdio.h>
#include <stdlib.h>

int line;// w ww  . ja v a  2  s .  c om

int product(int x, int y){
    return (x * y);
}

int main( int argc, char *argv[] ){
   char buffer[256];
   FILE *fp;

   if( argc < 2 ){
      fprintf(stderr, "\nProper Usage is: " );
      fprintf(stderr, "\n\nlist_it filename.ext\n" );
      return 1;
   }

   if (( fp = fopen( argv[1], "r" )) == NULL ){
        fprintf( stderr, "Error opening file, %s!", argv[1] );
        return(1);
   }

   line = 1;

   while( fgets( buffer, 256, fp ) != NULL ){
      fprintf( stdout, "%4d:\t%s", line++, buffer );
   }
   fclose(fp);
   return 0;
}

Result


Related Tutorials