Thursday, 9 November 2017

Write a program using LEX to recognize and count the number of identifiers in a given input file.

Source Code :

%{

#include<stdio.h>

int count=0;

%}

op [+-*/]

letter [a-zA-Z]

digitt [0-9]

id {letter}*|({letter}{digitt})+

notid ({digitt}{letter})+

%%

[\t\n]+

("int")|("float")|("char")|("case")|("default")| ("if")|("for")|("printf")|("scanf") {printf("%s is a keyword\n", yytext);}

{id} {printf("%s is an identifier\n", yytext); count++;}

{notid} {printf("%s is not an identifier\n", yytext);}

%%

int main()

{

FILE *fp;

char file[10];

printf("\nEnter the filename: ");

scanf("%s", file);

fp=fopen(file,"r");

yyin=fp;

yylex();

printf("Total identifiers are: %d\n", count);

return 0;

}

Output:

$cat > input

int

float

78f

90gh

a

d

are case

default

printf

scanf

$lex p3.l

$cc lex.yy.c –ll

$./a.out

Enter the filename: input

int is a keyword

float is a keyword

78f is not an identifier

90g is not an identifier

h is an identifier

a is an identifier

d is an identifier

are is an identifier

case is a keyword

default is a keyword

printf is a keyword

scanf is a keyword

total identifiers are: 4

No comments:

Post a Comment