标签:
1、本文中,需要将系统关键词自己首先定义在KeyWord数组中(如18行),这样程序才会自动进行比较;
2、选出某个关键词后,将其code置为0(如26行),避免多次打印该关键词;
3、请自己创建src.txt文件(如65行),并在里面放入一段“你需要统计的语言”代码。
//@Title:词法分析之关键词统计
//@Author:qingdujun
//@FileName:Main.CPP
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 8
//定义关键词结构体
typedef struct KeyWord
{
char name[30];
int code;
}KeyWord;
//定义关键词
KeyWord key[N] = {{"void",1},{"int",2},{"while",3},{"char",4},{"include",5},
{"typedef",6},{"struct",7},{"return",8}};
int isKeyWord(char *pChar)
{
int i;
for (i = 0; i < N; ++i)
{
if (0 == strcmp(pChar,key[i].name) && 0 != key[i].code)
{
key[i].code = 0;
return 1;
}
}
return 0;
}
//操作文件
void OpFile(FILE *fp)
{
int i = 0;
char ch;
char buf[30];//缓存
while (EOF != (ch = fgetc(fp)))
{
if ('a' <= ch && 'z' >= ch)
{
buf[i++] = ch;
}
else
{
buf[i] = '\0';
i = 0;
if (1 == isKeyWord(buf))
{//是关键词
printf("%s、",buf);
}
}
}
printf("\n");
}
//读取文件
void ReadFile()
{
FILE *fp = NULL;
//打开文件
if (NULL == (fp = fopen("src.txt","rb")))
{
printf("目标源文件不存在!\n");
exit(0);
}
//操作文件
OpFile(fp);
}
int main(void)
{
ReadFile();
return 0;
}标签:
原文地址:http://blog.csdn.net/qingdujun/article/details/44412823