我最近正在学编译原理,我有c语言实现的词法分析程序,不知可不可以,识别的是TEST语言的单词。
#include<stdio.h>
#include<ctype.h>
#include<string.h>
#define keywordSum 8
char * keyword[keywordSum] = {"do", "else", "for", "if", "int", "read", "while", "write"};
char singleword[50] = "+-*(){};,:";
char doubleword[10] = "><=!|&";
char Scanin[300], Scanout[300];
FILE * fin, * fout;
int binaryFind(int low, int high, char * c1, char ** c2) {
int mid;
if(low > high) return -1;
昌烂mid = (low+high)/2;
if(strcmp(c1, c2[mid]) == 0) return mid;
else if(strcmp(c1, c2[mid]) > 0) return binaryFind(mid+1, high, c1, c2);
else return binaryFind(low, mid-1, c1, c2);
耐肆漏 }
int TESTscan() {
char ch, token[40];
int es = 0, j, n;
printf("请输入源文件名(包括路径):");
scanf("%s", Scanin);
printf("请输入词雹搭法分析输出文件名(包括路径):");
scanf("%s", Scanout);
if((fin=fopen(Scanin, "r")) == NULL) {
printf("\n打开词法分析输入文件出错!\n");
return 1;
}
if((fout=fopen(Scanout, "w")) == NULL) {
printf("\n创建词法分析输出文件出错!\n");
return 2;
}
// printf("%c", getc(fin));
ch = getc(fin);
while(ch != EOF) {
while(ch==' ' || ch=='\n' || ch=='\t') {
ch = getc(fin);
}
if(isalpha(ch)) { //标识符
token[0] = ch;
j = 1;
ch = getc(fin);
while(isalnum(ch)) { //判断当前字符是否是字母或数字
token[j++] = ch;
ch = getc(fin);
}
token[j] = '\0';
// printf("%s", token);
n = binaryFind(0, keywordSum-1, token, keyword);
if(n < 0 ) {
fprintf(fout, "%s\t%s\n", "ID", token);
} else {
fprintf(fout, "%s\t%s\n", token, token);
}
} else if(isdigit(ch)) { //数字
token[0] = ch;
j = 1;
ch = getc(fin);
while(isdigit(ch)) {
token[j++] = ch;
ch = getc(fin);
}
token[j] = '\0';
fprintf(fout, "%s\t%s\n", "NUM", token);
} else if(strchr(singleword, ch) > 0) { //singleword
token[0] = ch;
token[1] = '\0';
ch = getc(fin);
fprintf(fout, "%s\t%s\n", token, token);
} else if(strchr(doubleword, ch) > 0) { //doubleword
token[0] = ch;
ch = getc(fin);
if(ch=='=' && (token[0]=='>'||token[0]=='<' || token[0] == '!')) {
token[1] = ch;
token[2] = '\0';
ch = getc(fin);
} else if((ch=='&')||(ch=='|')||(ch=='=') && ch==token[0]) {
token[1] = ch;
token[2] = '\0';
ch = getc(fin);
} else {
token[1] = '\0';
}
fprintf(fout, "%s\t%s\n", token, token);
} else if(ch == '/') { //注释
ch = getc(fin);
if(ch == '*') {
char ch1;
ch1 = getc(fin);
do {
ch = ch1;
ch1 = getc(fin);
} while((ch!='*'||ch1!='/') && ch1!=EOF);
ch = getc(fin);
} else {
token[0] = '/';
token[1] = '\0';
fprintf(fout, "%s\t%s\n", token, token);
}
} else {
token[0] = ch;
token[1] = '\0';
ch = getc(fin);
es = 3;
fprintf(fout, "%s\t%s\n", "ERROR", token);
}
}
fclose(fin);
fclose(fout);
return es;
}
void main() {
int es = 0;
es = TESTscan();
if(es > 0) {
printf("词法分析有错, 编译停止!\n");
} else {
printf("词法分析成功!\n");
}
}