Linux教程網
C語言統計源文件關鍵字的個數
- #include <stdlib.h>
- #include <stdio.h>
-
- #define MAX_WORD 128;
- #define MAX_LEN 100
-
- typedef struct _Key{
- char* keyWord;
- int cout;
- }KeyWord;
-
- //初始化
- KeyWord keyTab[]={
- "auto",0,
- "break",0,
- "case",0,
- "char",0,
- "const",0,
- "continue",0,
- "default",0,
- "define",0,
- "unsigned",0,
- "void",0,
- "volatile",0,
- "while",0
- };
- //獲取長度
- size_t getLen(void)
- {
- return (sizeof keyTab /sizeof keyTab[0]);
- }
- //打印
- void printKey(KeyWord key[],size_t len)
- {
-
- int i;
- for(i=0;i<len;i++)
- {
- printf("%4d %s\n",key[i].cout,key[i].keyWord);
- }
- }
-
- //從文件中獲取一個單詞
- int getWord(char* word,int len,FILE* f){
- char* w = word;
- int c;
- //跳過空格
- while(isspace(c=fgetc(f)))
- ;
- if(c!=EOF)
- *w++ = c;
- //不是字母
- if(!isalpha(c))
- {
- *w='\0';
- return c;
- }
- for(;--len>0;w++)
- {
- if(!isalnum(*w=fgetc(f)))
- {
- ungetc(*w,f);
- break;
- }
- }
- *w = '\0';
- return c;
- }
- //二分查找
- int binSearch(KeyWord k[], char* word,int len)
- {
- int low,high,mid,pos;
- low=0;
- high=len-1;
- while(low<=high)
- {
- mid = (high+low)/2;
- //如果word比key[mid].keyword小 下次循環在[low~mid-1]之間找
- if((pos=strcmp(word,k[mid].keyWord))<0)
- {
- high = mid-1;
- }else if(pos>0){
- low = mid+1;
- }else{
- return mid;
- }
- }
- return -1;
- }
- //FindKeyW.h
- //main.c
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include "FindKeyW.h"
-
- int main(int argc, char *argv[])
- {
- extern KeyWord keyTab[];
- size_t len = getLen();
- FILE* f;
- if(f=fopen("FindKeyW.h","r"))
- {
- char word[MAX_LEN];
- int pos;
- while(getWord(word,MAX_LEN,f)!=EOF)
- {
- if(isalpha(word[0]))
- {
- if((pos=binSearch(keyTab,word,len))>0)
- {
- keyTab[pos].cout++;
- }
- }
- }
- fclose(f);
- }
- printKey(keyTab,len);
- system("PAUSE");
- return 0;
- }
Copyright ©
Linux教程網 All Rights Reserved