Wednesday 8 February 2017

C program to count number of lines, words and characters in a file

File handling is an important concept in any programming language. The data needed to run a program can be stored permanently in a file and can be taken as input to the program from the file at any time. The following program reads any given file and displays the number of lines, words and characters contained in the file.

//Program to count number of characters, words and lines in a file
#include<stdio.h>
#include<conio.h>
main()
{
  FILE *fp;
  int cc=0,wc=0,lc=0;
  char c,pc='\0',*fname;

  clrscr();
 /* if (argc<2)
  {
    printf("Less number of arguments");
    exit();
  }              */
  printf("Enter the file name\n");
  scanf("%s",fname);
  fp=fopen(fname,"r");
  if (fp==NULL)
  {
     printf("Error in opening the file");
     exit();
  }
  while ((c=fgetc(fp))!=EOF)
  {
     cc++;
     if (cc==1)
     lc=1;
     if (c=='\n')
     lc++;
     if ((c==' ' || c=='\n' ) && (pc!=' ' && pc!='\n'))
     wc++;
     pc=c;
   }
   if (c==EOF && pc!='\n')
   wc++;
   printf("The file  contains %d lines, %d words and %d characters",lc,wc,cc);
   getch();
}
/*
test.dat
---------
hello
   welcome hai
how are you


OUTPUT
---------
Enter the file name
test.dat
The file  contains 3 lines, 6 words and 32 characters
*/                                                    




No comments:

Post a Comment