C program to Design a lexical analyzer for given language

 LOGIC: 1. Read the input Expression 2. Check whether input is alphabet or digits then store it as identifier 3. If the input is is operator store it as symbol 4. Check the input for keywords

				
					#include<string.h> 
#include<ctype.h> 
#include<stdio.h> 
void keyword(char[]); 
void main() 
{
FILE *f1,*f2,*f3; 
char c,str[10],st1[10]; 
int num[100],lineno=0,tokenvalue=0,i=0,j=0,k=0; 
clrscr(); 
printf("\nEnter the c program\n"); 
f1=fopen("input.txt","w"); 
while((c=getchar())!=EOF) 
putc(c,f1); 
fclose(f1); 
f1=fopen("input.txt","r"); 
f2=fopen("identifier.txt","w"); 
f3=fopen("specialchar.txt","w"); 
while((c=getc(f1))!=EOF) 
{ 
if(isdigit(c)) 
{ 
tokenvalue=c-48; 
c=getc(f1); 
while(isdigit(c)) 
{ 
tokenvalue=tokenvalue*10+(c-48); 
c=getc(f1); 
}
num[i++]=tokenvalue;
ungetc(c,f1); 
}
else if(isalpha(c)) 
{ 
putc(c,f2); 
c=getc(f1); 
while(isdigit(c)||isalpha(c)||c=='_'||c=='$') 
{ 
putc(c,f2); 
c=getc(f1); 
}
putc(' ',f2); 
ungetc(c,f1); 
}
else if(c==' '||c=='\t') printf(" "); 
else if(c=='\n') 
lineno++; 
else 
putc(c,f3); 
}
fclose(f2); 
fclose(f3); 
fclose(f1);
printf("\nThe numbers in the program are:"); 
for(j=0;j<i;j++) printf(" %d ",num[j]); 
printf("\n"); f2=fopen("identifier.txt","r"); k=0; printf("The keywords and identifiersare:"); 
while((c=getc(f2))!=EOF) 
{ 
if(c!=' ') 
str[k++]=c; 
else 
{ 
str[k]='\0';
keyword(str); 
k=0;
} 
} 
fclose(f2); 
f3=fopen("specialchar.txt","r");
printf("\nSpecial characters are");
while((c=getc(f3))!=EOF) 
printf(" %c ",c); 
printf("\n"); 
fclose(f3); 
printf("Total no. of lines are:%d",lineno); 
getch(); 
}
void keyword(char str[10]) 
{ 
if(strcmp("for",str)==0||strcmp("while",str)==0||strcmp("do",str)==0|| strcmp("int",str)==0||strcmp("float",str)==0||strcmp("char",str)==0|| strcmp("double",str)==0||strcmp("static",str)==0|| strcmp("switch",str)==0||strcmp("case",str)==0) 
// TYPE 32 KEYWORDS 
printf("\n%s is a keyword",str); 
else 
printf("\n%s is an identifier",str); 
}
				
			
OUTPUT
Enter the c program
int main()
{
int a=10,20;
char ch;
float f;
}^Z
The numbers in the program are: 10 20
The keywords and identifiersare:
int is a keyword
main is an identifier
int is a keyword
a is an identifier
char is a keyword
ch is an identifier
float is a keyword
f is an identifier
Special characters are ( ) { = , ; ; ; }
Total no. of lines are:5

Leave a Reply