Program : Lexical Analyzer
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main() //main function
{
FILE *p;
int i=0,j=0,k=0,flag;
char x,temp[100];
char digit[10]={'0','1','2','3','4','5','6','7','8','9'};
char key[25][10]={"auto","break","case","char","const","continue",
"default","do","double","else","enum","for",
"goto","if","int","return","signed","static",
"struct","union","while","switch","void","float"};
char opera[10][17]={"+","=","*","/","-",">","<"};
clrscr();
p=fopen("text.txt","r"); //open file
if(p==NULL) //if file not present
printf("cannot open the file");
else
{
printf("\tKEYWORD\tIDENTIFIER\tOPERATOR\n");
while((x=fgetc(p))!=EOF)
{
if((x!=' ')&&(x!='\t')&&(x!='\n')) //get keyword
{
temp[i]=x;
i++;
temp[i]='\0';
}
else
{
for(j=0;j<i;j++)
temp[j]=' ';
i=0;
}
for(k=0;k<25;k++) //compare with key
{
if(strcmp(temp,key[k])==0)
{
printf("\n\t%s",temp);
for(j=0;j<i;j++)
temp[j]=' ';
i=0;
}
}
for(j=0;j<strlen(temp);j++) //check identifiers
{
for(k=0;k<11;k++)
{
flag=0;
if(temp[j]==digit[k])
{
flag=1;
break;
}
}
}
if(flag!=0)
{
printf("\n\t\t%s",temp);
for(j=0;j<i;j++)
temp[j]=' ';
i=0;
}
for(k=0;k<10;k++) //check if operator
{
if(strcmp(temp,opera[k])==0)
{
printf("\n\t\t\t\t%s",temp);
for(j=0;j<i;j++)
temp[j]=' ';
i=0;
}
}
}
}
fclose(p); //close the file
getch();
}
0 comments:
Post a Comment