首页 > 代码库 > 词法分析

词法分析

词法分析程序的功能:

一个具体的词法分析程序,从输入的源程序中,识别出各个具有独立意义的单词,即基本关键字、标识符、数字、运算符、分隔符五大类。并依次输出各个单词的内部编码及单词符号自身值。

符号与种别码对照表:

技术分享

用文法描述词法规则:

〈标识符〉→l|l〈字母数字〉
〈字母数字〉→l|d|l〈字母数字〉|d〈字母数字〉
〈无符号整数〉→d|d〈无符号整数〉
〈运算符〉→+|-|*|/|=|〈〈等号〉|〉〈等号〉……
〈等号〉→=
〈界符〉→,|;|(|)|……
再比如:
C→aCA  Ba→aB
C→bCB  Bb→bB
AD→aD  C→ε
BD→bD  D→ε
Aa→bD

 

源代码:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void Analyse(FILE *fp,char ch);
main()
{
FILE *fp;
char ch;
printf("请输入源程序代码(以#键结束):\n");
if((fp=fopen("data.txt","w"))==NULL)
{
printf("Failure to open data.txt!\n");
exit(0);
}
ch=getchar();
while(ch!=‘#‘)//将字符串存放到文件中
{
fputc(ch,fp);
ch=getchar();
}
fclose(fp);
if((fp=fopen("data.txt","rb"))==NULL)
{
printf("Failure to open data.txt!\n");
exit(0);
}
ch=fgetc(fp);
Analyse(fp,ch);
}
void Analyse(FILE *fp,char ch) 
{
char keyword[40][40]={"include","auto","break","case","char","const","continue","default","do","double","else","enum","extern","float","for","goto","if","int","long","return","short","sizeof","static","struct","switch","typedef","union","void","while"};
int i=0,j,flag;
int n=0,m;
char alp[20];
char num[11];
FILE *fp1;
FILE *fp2;
while(!feof(fp))
{
if(ch==‘+‘||ch==‘-‘||ch==‘*‘||ch==‘/‘||ch==‘%‘||ch==‘=‘||ch==‘>‘||ch==‘<‘)//判断判断运算符
printf("%c\t运算符\n",ch);
else if(ch==‘;‘||ch==‘{‘||ch==‘}‘||ch==‘(‘||ch==‘)‘)//判断分隔符
printf("%c\t分隔符\n",ch);
else if(ch>=‘a‘&&ch<=‘z‘||ch>=‘A‘&&ch<=‘Z‘)//判断字符是不是字母
{
if((fp1=fopen("data1.txt","w"))==NULL)

printf("Failure to open data1.txt!\n");
exit(0);
}
while(ch>=‘a‘&&ch<=‘z‘||ch>=‘A‘&&ch<=‘Z‘)//将每个字母合并成一个字符串放到有个新的文件中
{
fputc(ch,fp1);
i++;
ch=fgetc(fp);
}
fclose(fp1);
if((fp1=fopen("data1.txt","rb"))==NULL)

printf("Failure to open data1.txt!\n");
exit(0);
}
fgets(alp,i+1,fp1);
for(j=0;j<30;j++)
{
if(strcmp(alp,keyword[j])==0)//判断是否为关键字或标识符
flag=1;
}
if(flag==1)
printf("%s\t关键字\n",alp);
else
printf("%s\t标识符\n",alp);
fclose(fp1);
Analyse(fp,ch);
}
else if(ch==‘\n‘||ch==‘ ‘)//识别回车和空格
printf("\r");
else if(ch>=‘0‘&&ch<=‘9‘)//识别数字
{
if((fp2=fopen("data2.txt","w"))==NULL)

printf("Failure to open data2.txt!\n");
exit(0);
}
while(ch>=‘0‘&&ch<=‘9‘)
{
fputc(ch,fp2);
n++;
ch=fgetc(fp);
}
fclose(fp2);
if((fp2=fopen("data2.txt","rb"))==NULL)

printf("Failure to open data2.txt!\n");
exit(0);
}
fgets(num,n+1,fp2);
printf("%s\t数字\n",num);
fclose(fp2);
Analyse(fp,ch);
}


ch=fgetc(fp);//放到所有if后面



}


}

截图:

技术分享

 

词法分析