Tuesday, 16 September 2014

LEX PROGRAM TO COUNT THE NUMBER OF CHARACTERS,WORDS,SPACES AND LINES

program :

%{
int ch=0,wd=0,l=0,sp=0;
%}
%%
(" ") {sp++;}
[\n] {l++;}
[^ \t \n]+ {wd++; ch=ch+yyleng;}
%%
main()
{
yyin=fopen("kit.txt","r");
yylex();
printf("char=%d \t words=%d \t spaces=%d \t lines=%d",ch,wd,sp,l);
}

STEP1:
  Each yac program consist of 3 parts

                                 Definition --
                                 %%
                                 Rules --
                                 %%
                                 Subroutines --

after compiling yac program is converted into equivalent c program. In that definition part of yac is introduced without any modification.
so in the above program ch=0,wd=0,l=0,sp=0 are globally declared.

STEP2:
     (" ") matches the space character when it encounters a space character sp will be incremented. [\n] matches the single new line character l will be incremented when lex encounters a new line in the file.
[^ \t \n]+ -----> ^ implies negation of operators present to next to it
                            it matches string of any number of digits or characters and/or both. which is nothing but a word. hence wd will be incremented each time and yyleng is inbuilt method that gives the length of each word. Hence the instruction
     ch=ch+yyleng.

STEP3:
         kit.txt consist of some data
         Above program must be saved with .l extension
 to compile and run use following commands
 $ lex program_name.l
 $ cc lex.yy.c -ll
 $./a.out

  

4 comments:

  1. This is my first time visit here. From the tons of comments on your articles,I guess I am not only one having all the enjoyment right here! view

    ReplyDelete

Total Pageviews

108295