www.pudn.com > 编译原理实验一.rar > BY1.C


/*作者:吴拓,于2005年12月15日凌晨4:25分完成*/ 
#include 
main() 
{ 
	/*打开文件*/ 
	FILE *fp; 
	char ch,ch2,filename[10],wordbuff[100]; 
	int i=0; 
	printf("input filename:"); 
	scanf("%s",filename); 
	while((fp=fopen(filename,"r"))==NULL) 
	{ 
		printf("cannot open file,Please input filename again!(Ctrl+C exit)"); 
		scanf("\n%s",filename); 
	} 
 
	ch=fgetc(fp);/*扫描一个字符*/ 
	wordbuff[i++]=ch;/*将这个字符存入单词空间*/ 
	while(ch==' '||ch=='\n'||ch=='\t')/*是否是空格、回车、制表符,是则重取字符*/ 
	{ 
		ch=fgetc(fp); 
		i=0; 
		wordbuff[i++]=ch; 
	} 
	wordbuff[i]='\0';/*字符串结束*/ 
	ch2=fgetc(fp); 
	while(ch!=EOF)/*无字符则结束程序*/ 
	{ 
		if(chartype(ch)!=5)/*是否为分隔符,是则即时输出,否则与后一个字符比较,同类字符继续取出,存入单词空间*/ 
			while(chartype(ch)==chartype(ch2)) 
			{	wordbuff[i++]=ch2; 
				wordbuff[i]='\0'; 
				ch2=fgetc(fp); 
			} 
		printf("(%d,\"",wordtype(wordbuff)); 
		printf("%s\")\n",wordbuff); 
		ch=ch2; 
		i=0; 
		wordbuff[i++]=ch; 
		while(ch==' '||ch=='\n'||ch=='\t') 
		{ 
			ch=fgetc(fp); 
			i=0; 
			wordbuff[i++]=ch; 
		} 
		wordbuff[i]='\0'; 
		ch2=fgetc(fp); 
	} 
} 
 
 
int chartype(char ch)/*判断字符的类型*/ 
{ 
	if(ch==','||ch==';'||ch=='{'||ch=='}'||ch=='('||ch==')') 
		return 5; 
	if(ch=='+'||ch=='-'||ch=='*'||ch=='/'||ch=='='||ch=='>'||ch=='<'||ch=='!') 
		return 4; 
	if((ch>='A'&&ch<='Z') || (ch>='a'&&ch<='z') || (ch>='0'&&ch<='9') ) 
		return 1; 
	return 0; 
} 
 
int wordtype(char ch[])/*判断单词的类型*/ 
{ 
	if(strcmp(ch,",")==0) 
		return(5); 
	if(strcmp(ch,";")==0) 
		return(5); 
	if(strcmp(ch,"{")==0) 
		return(5); 
	if(strcmp(ch,"}")==0) 
		return(5); 
	if(strcmp(ch,"(")==0) 
		return(5); 
	if(strcmp(ch,")")==0) 
		return(5); 
	if(strcmp(ch,"+")==0) 
		return(4); 
	if(strcmp(ch,"-")==0) 
		return(4); 
	if(strcmp(ch,"*")==0) 
		return(4); 
	if(strcmp(ch,"/")==0) 
		return(4); 
	if(strcmp(ch,"=")==0) 
		return(4); 
	if(strcmp(ch,">")==0) 
		return(4); 
	if(strcmp(ch,"<")==0) 
		return(4); 
	if(strcmp(ch,">=")==0) 
		return(4); 
	if(strcmp(ch,"<=")==0) 
		return(4); 
	if(strcmp(ch,"!=")==0) 
		return(4); 
	if(isnumber(ch)==1) 
		return(3); 
	if(strcmp(ch,"main")==0) 
		return(1); 
	if(strcmp(ch,"if")==0) 
		return(1); 
	if(strcmp(ch,"int")==0) 
		return(1); 
	if(strcmp(ch,"for")==0) 
		return(1); 
	if(strcmp(ch,"while")==0) 
		return(1); 
	if(strcmp(ch,"do")==0) 
		return(1); 
	if(strcmp(ch,"return")==0) 
		return(1); 
	if(strcmp(ch,"break")==0) 
		return(1); 
	if(strcmp(ch,"continue")==0) 
		return(1); 
	else 
		return(2); 
} 
 
int isnumber(char ch[])/*判断字符串是否表示数值*/ 
{ 
	int j; 
	for (j=0;ch[j]!='\0';j++ ) 
	{ 
		if((ch[j]<'0') ||(ch[j]>'9')) 
		{ 
			return 0; 
		} 
	} 
	return 1; 
}