Saturday 9 January 2016

LEX YACC To Parse Input Text File

            In this post, we will see how to provide text file as input to Lex Yacc program. Here we will take example of arithmetic expression evaluation which takes arithmetic expressions from a text file.
           yyin is standard file pointer which is defined by lex yacc library. So that, just we have to declare it in yacc file by using keyword extern.
           
            Go through the following program:





Program: (sample.txt)


2+3*5
5+3-4
5+5-5*5
6+4/2-3

Program: (sample.l)
%{
#include<stdio.h>
#include "y.tab.h"
extern int yylval;
%}

%%
[0-9]+ {
          yylval=atoi(yytext);
          return NUMBER;
       }
[\t] ;
[\n] return 0;
. return yytext[0];
%%
int yywrap()
{
return 1;
}

Program:(sample.y)
 %{
    #include<stdio.h>
    int flag=0;
    extern FILE *yyin;
 
%}
%token NUMBER

%left '+' '-'
%left '*' '/' '%'
%left '(' ')'
%%
ArithmeticExpression: E{
         printf("\nResult=%d\n",$$);
         return 0;
        }
E:E'+'E {$$=$1+$3;}
 |E'-'E {$$=$1-$3;}
 |E'*'E {$$=$1*$3;}
 |E'/'E {$$=$1/$3;}
 |E'%'E {$$=$1%$3;}
 |'('E')' {$$=$2;}
 | NUMBER {$$=$1;}
;
%%

void main()
{
   FILE *fp; int i;
   fp=fopen("sample.txt","r");
   yyin=fp;
 
 for(i=0;i<4;i++)
   yyparse();

  if(flag==0)
   printf("\nEntered arithmetic expression is Valid\n\n");

}
void yyerror()
{
   printf("\nEntered arithmetic expression is Invalid\n\n");
   flag=1;
}

Output: 

No comments:

Post a Comment