Compiler Design Lab4
Compiler Design Lab4
1. Design a lex code to print number of lines, spaces, characters, tabs and
words in given “Input.txt” file
%{
#include<stdio.h>
#include<string.h>
int sc=0,lc=0,cc=0,tc=0,wc=0;
%}
%%
\n[a-zA-Z] {lc++; wc++; }
\n {lc++;}
[" "][" "][" "][" "][a-zA-Z] {tc++; wc++;}
[" "][" "][" "][" "] {tc++;}
[" "][a-zA-Z] {wc++; sc++;}
[" "] {sc++;}
. {cc++;}
end return 0;
%%
int yywrap(){}
int main()
{
extern FILE *yyin;
yyin = fopen("Input.txt", "r");
yylex();
printf("\nThe number of lines=%d\n",lc);
printf("The number of spaces=%d\n",sc);
printf("The number of characters=%d\n",cc);
printf("The number of tabs=%d\n",tc);
printf("The number of words=%d\n",wc);
return 0;
}
Input.txt file
Hii Hello
How are you
end
Output
3.Design a lex code to remove the comments from any C program given at run
time and store in “out.c” file
%{
#include<stdio.h>
%}
%%
[\/][\/].* {;}
[\/][\*].*[\*][\/] {;}
. {fprintf(yyout,"%s",yytext);}
%%
int yywrap(){}
int main()
{
yyin=fopen("input1.c","r");
yyout=fopen("out.c","w");
yylex();
return 0;
}
Output