0% found this document useful (0 votes)
26 views

Lex Prgms

The document describes two LEX programs. The first program counts the number of lines and characters in a file. The second program is a scanner that tokenizes a C program and prints the tokens along with their length and line number. Both programs generate a lex.yy.c file that needs to be compiled and executed, taking a file name as input to perform the scanning/counting.

Uploaded by

Naveen Kumar
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

Lex Prgms

The document describes two LEX programs. The first program counts the number of lines and characters in a file. The second program is a scanner that tokenizes a C program and prints the tokens along with their length and line number. Both programs generate a lex.yy.c file that needs to be compiled and executed, taking a file name as input to perform the scanning/counting.

Uploaded by

Naveen Kumar
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 2

2.LEX Program to count No.

of Lines and Characters in a file


%option noyywrap %{ #include<stdio.h> int num_lines=0,num_chars=0; %} char . line \n %% {line} {++num_lines; printf("\n%d. ",num_lines);} {char} {++num_chars; printf("%s",yytext);} %% main(int argc,char* argv[]) { FILE *fd; if(argc < 2) { printf("file name is not given\n"); } else { if((fd=fopen(argv[1],"r"))<0) { printf("error\n"); exit(0); } } yyin = fd; yylex(); printf("# of lines = %d, # of chars = %d\n", num_lines, num_chars ); }

Executing the above program:

$lex no_lines.l A file named lex.yy.c is generated. $cc lex.yy.c $./a.out <<filename>>

3. Scanner program using LEX

scanner.l
%{ #include<stdio.h> int lineno=1; %} %option noyywrap %% "/n" lineno++; int|float|char|if|else|break|switch|continue|case|while|do|for {printf("%s keyword,length %d,lineno %d\n",yytext,yyleng,lineno);} [a-zA-Z]([a-zA-Z|0-9])* {printf("%s identifier,length %d,lineno %d\n",yytext,yyleng,lineno);} ";" {printf("; SEMI");} ">=" {printf(">= GTE");} "<>" {printf(">= NTE");} "<" {printf(">= LT");} "<=" {printf(">= LTE");} ">" {printf(">= GT");} "{" "}" "(" {printf("LEFT PARAN");} ")" {printf("RIGHT PARAN");} "++" {printf("UNARY PLUS");} "__" {printf("UNARY MINUS");} "+" {printf("%s plus", yytext);} "_" {printf( " - MINUS");} "*" {printf(" * mul");} "%" {printf("% mod");} "/" {printf("/ divide");} %% main(int argc,char *argv[]) { FILE * fd; fd=fopen(argv[1],"r"); yyin=fd; yylex(); return 0; }

Executing the above program:

$lex scanner.l A file named lex.yy.c is generated. $cc lex.yy. $./a.out <<sample C filename>>

You might also like