/* Author: bhw EMail: bhwshx@163.com Date: 2009年03月04日 星期三 */ //Function: 寻找和计数文件中的指定词 #include<stdio.h> #include<string.h> typedef struct { char *key; int count; }KEYWORDS; KEYWORDS keyword[6] = { {"char", 0}, {"int", 0}, {"long", 0}, {"float", 0}, {"void", 0}, {"return", 0} }; char *getWord(FILE *fp) { char ch; static char buf[100]; int i = 0; while(((ch = fgetc(fp)) != EOF) && ((ch == ' ')||(ch == '/t')||(ch == '/n'))) ;//here is nothing if(ch == EOF) return NULL; else { buf[i++] = ch; } while(((ch = fgetc(fp)) != EOF) && (ch != ' ') && (ch != '/t') && (ch != '/n')) buf[i++] = ch; buf[i] = '/0'; return buf; } void wordSearch(char *p) { int i; for(i=0; i<6; ++i) { if(strcmp(p, keyword[i].key) == 0) { keyword[i].count++; break; } } } int main(int argc, char *argv[]) { FILE *fp; char *p; int i; if(argc != 2) { printf("Usage:%s [file name]/n",argv[0]); return 0; } fp = fopen(argv[1],"r"); if(fp == NULL) { printf("Open %s failed/n",argv[1]); return 0; } else { while((p = getWord(fp)) != NULL) wordSearch(p); } fclose(fp); printf("Results:/n"); for(i=0; i<6; ++i) { printf("%s :%d/n", keyword[i].key, keyword[i].count); } return 0; }