Files - 4 Example on Files

/* Program to count number of lines  and character */
 
#include< stdio.h >
#include< stdlib.h >
main()
{
FILE *fp;
char c,fname[20];
int count=0,lcount=0, chcount=0;
printf( "\n Enter the file name ");
gets(fname);
x:
fp=fopen( fname, "r" );
if(fp == NULL)
  {
   printf ( "\n Error in opening the file  \n \n Enter the file name once again  ");
   gets(fname);
   count++;
   if( count == 3)
     exit(1);
   goto x;
  }
else
  while( 1 )
    {
     c = getc( fp );
     if(c==EOF) break;
     chcount++;
     if( c=='\n')
    lcount++;
    }
printf("\n Number of lines = %d \n  Number of characters = %d ", lcount,  chcount);
}

In the above program initially  required variables are declared. A  file name is accepted and opened  using fopen() function. If it returns  NULL a proper error message is  displayed and asked to enter the  correct file name also a variable  count is incremented by 1 and this  process is repeated for until count  becomes 3 and then same repeats  the program will exit. If the file name  is entered correctly and if it exists  then it enters into while loop where  it reads a character. It checks for  EOF(end of file) if so it quits the loop  and continues with the remaining  part of the program. If not character  counting variable chcount will be  incrementd by 1 and checks for new  line character '\n' if it is then line  count variable lcount will be  incremented by 1. At last it prints the  number of lines and characters  present in the given file name.

Comments