C Programming
Computer Programming

C file handling program to find number of lines in a file



Write C file handling program to find number of lines in a file

\* C file handling program to find number of lines in a file *\

# include < stdio.h >
int   main( )
{

FILE *fp ;
char ch, FILENAME[30] ;
int linesCount = 0 ;

//open file in read more
printf("\n Enter the filename to be opened : ") ;
scanf("%s",FILENAME ) ;
fp = fopen(FILENAME, "r" ) ;
if( fp == NULL )
{
      printf(" File \"%s\" does not exist!!!\n", FILENAME ) ;
      return -1 ;
}

//read character by character and check for new line
while( (ch=fgetc(fp))!=EOF )
{
      if( ch == '\n' )
            linesCount++ ;
}

//close the file
fclose(fp) ;

//print number of lines
printf(" Total number of lines are: %d\n", linesCount ) ;
return 0 ;

}

Output of Program :

Output of C file handling program to find number of lines in a file