Program to count the number of lines, number of words, number of blank spaces and number of character in a file

%{
#include<stdio.h>
int cc=0,bc=0,wc=0,lc=0;
%}
%%
[^ \t\n]+  { wc++;
             cc=cc+yyleng;
           }
\n   lc++;
" "  bc++;
\t   bc=bc+5;
%%
main(int argc,char *argv[])
{
     if (argc!=2)   {
          printf("\nusage:./a.out filename\n");
          return(0);
     }
     yyin=fopen(argv[1],"r");
     yylex();
     printf("\n no of lines are %d\n",lc);
     printf("\n no of words are %d\n",wc);
     printf("\n no of blanks are %d\n",bc);
     printf("\n no of character are %d\n",cc);
}
int yywrap()
{
    return 1;
}

Sample Input\Output:
[united@localhost ~]$ vi lexpart.l
[united@localhost ~]$ lex lexpart.l
[united@localhost ~]$ gcc lex.yy.c
[united@localhost ~]$ vi file.c
[united@localhost ~]$ ./a.out file.c
no of lines are 3
no of words are 9
no of blanks are 8
no of character  are 21
[united@localhost ~]$

About these ads

About Devesh Kumar

I love programming !
This entry was posted in C, Compiler Design and tagged , , , , , , , . Bookmark the permalink.

2 Responses to Program to count the number of lines, number of words, number of blank spaces and number of character in a file

  1. Dev says:

    @kalpana
    Can you tell me plzz what kind of error you have found?

    Like

  2. kalpana verma says:

    the program is giving error!!!!!!

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s