Program to count the number of characters ,lines and words a in a text file.


C File =>


/* Write a program to read the contents of a text file and count the number of characters, lines and words in the file. */


#include<stdio.h>
#include<stdlib.h>
int main()
{
      FILE *fp;
      char ch;
      int lcnt=1,wcnt=0,cnt=0;
      fp=fopen("a.txt","r");
      if(!fp)
           printf("\n Error in reading");
      else
     {
          while((ch=fgetc(fp))!=EOF)
          {
             cnt++;
             printf("%c",ch);
             if(ch=='\n')
            {
                   lcnt++;
                   wcnt++;
             }
             if(ch==' ')
                  wcnt++;
           }
         printf("\n Character count = %d",cnt);
         printf("\n Line count = %d",lcnt);
         printf("\n Word count = %d",wcnt);
      }
     return 0;
}

Comments

Popular posts from this blog

Write a program to allocate memory dynamically for n integers. Accept the elements and calculate their sum and average

C program to accept names of n cities and search for city named “Pune”.