#include<stdio.h>#include<stdlib.h>#include<iostream.h>#include<string.h>
#define KEYNUM 32 //c语言中的关键字个数 32#define KEYMAX 8 //最大关键字字节个数 8
const char Key[KEYNUM][KEYMAX+1]= //把32个关键字存储在二维数组Key中{ "auto","break","case","char","const","continue","default","do","double", "else","enum","extern","float","for","goto","if","int","long","register", "return","short","signed","sizeof","static","struct","switch","typedef", "union","unsigned","void","volatile","while"};
const char split[26]=" ();'~:+-<>_.|/{,!#&*///"/t/n"; //分割依据:源程序中可能出现的所有字符
void welcome();void statistics();
void welcome() //欢迎界面{ printf("┏━━━━━━━━━━━━━━━━━━━━━━━━━━━┓/n"); printf("┃ ▲ ▲ ┃/n"); printf("┃ ■▁▁欢迎使用统计C程序关键字频率程序▁▁▁■ ┃/n"); printf("┃ ╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬ ┃/n"); printf("┃ ┃/n"); printf("┃ ┃/n"); printf("┃ 注意:统计结果默认保存在C://keyword.txt中 ┃/n"); printf("┃ ┃/n"); printf("┗━━━━━━━━━━━━━━━━━━━━━━━━━━━┛/n");}
void statistics() //统计函数{ FILE *fp1,*fp2; int num = 0,i,j = 0,k; char cha[250],che[250]; char *p; char filename[20]; printf("请输入文件名及路径:/n"); //输入所要统计的源程序文件路径 scanf("%s",filename); printf("The result :/n");
if((fp1=fopen(filename,"r"))==NULL) //打开源程序文件 { printf("Can not open flie/n"); exit(1); }
if((fp2=fopen("c://keyword.txt","w"))==NULL) //打开或新建存储统计结果的文件c://keyword.txt { printf("Can not open flie/n"); exit(1); }
for(k=0;k<KEYNUM;k++) { while(!feof(fp1)) { fgets(cha,sizeof(cha),fp1); //从源程序文件中分块获取指定字节内容 strcpy(che,cha); p = strtok(che,split); while(p!=NULL) { strcpy(che,cha); p = strtok(che,split); //按照分割依据将获取内容进行分割,并存储在che中 for(i=0;i<j;i++) { p=strtok(NULL,split); } if(p!=NULL) { if(strcmp(p,Key[k])==0) //分割取出的字符串与关键字比较,如果相同计数加一 { num++; } } j++; } j=0; } rewind(fp1); //比较完一个关键字,指针返回源程序文件开头 printf("%-10s]/n",Key[k],num); //将统计结果显示在屏幕上 fprintf(fp2,"%-10s]/n",Key[k],num); //将统计结果记录在指定文件中 num=0; } fclose(fp1); //关闭源程序文件 fclose(fp2); //关闭记录统计结果的文件 }
int main() //主函数{ welcome(); //调用欢迎界面函数 statistics(); //调用统计函数 return 0;}