Write a program to count the number of lines and characters in a text file.

#include<stdio.h>
#include<conio.h>

//NOTE:if using TurboC count.txt is in C:\TC\BIN
void main()
{
FILE *fp;
char c;
int ccount=0,lcount=0;
clrscr();

fp=fopen("count.txt","r"); //open count.txt file in read mode

if(fp==0)
  printf("File does not exist\n");
else
{
  //count no. of lines and no. of characters
  while(!feof(fp))
  {
    c=getc(fp); //get every character of file count.txt
    putchar(c); //print every character of file count.txt

    if(c=='\n')
      lcount++;
    else
      ccount++;
  }
printf("\nNumber of lines=%d\n",lcount);
printf("\nNumber of characters=%d\n",ccount);

}
getch();
fclose(fp); //close the file pointed by fp
}

 

Please follow and like us:

Leave a Comment