count frequency of occurrence of a word - lex program

 LEX code to count the frequency of the given word(sachin)  in an input.txt file

***************************************************

%{

#include<stdio.h>

#include<string.h>

char word [] = "sachin";

int count = 0;

%}

%option noyywrap

/* Rule Section */

%%

[a-zA-Z]+ { if(strcmp(yytext, word)==0)

                                count++; }

.     ;

\n     ;

%%

/* code section */

int main()

{

                extern FILE *yyin, *yyout;

                /* open the input file

                in read mode */

                yyin=fopen("input.txt", "r");

                yylex();

                printf("No of occurance of the word %s=%d\n",word, count);

}

Execution
the input.txt file is
$ cat input.txt
this is a test file
to check frequncy of the word sachin
it will count how many times word sachin
occures in the file and count the word sachin

$ flex freq.lex
$ gcc lex.yy.c
$ ./a.out
No of occurance of the word sachin=3

Comments

Popular posts from this blog

KTU Compiler Lab CSL411 - Dr Binu V P

lexical analyzer for a c program

13.Precedence and conflict resolution in yacc