サイトマップ / C言語講座>出入り口>総目次>目次:ファイル>二分木探索(バイナリサーチ)||デモ用
ファイル名を”Wtest.c”に変更し、コンパイル済のソースと同じフォルダに置いて下さい。
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #define NUM_KW 25 typedef struct { char name[10] int count; } KEYWORD; KEYWORD keyword[NUM_KW] = { {"break", 0}, {"case", 0}, {"char", 0}, {"continue", 0}, {"do", 0}, {"double", 0}, {"else", 0}, {"enum", 0}, {"extern", 0}, {"float", 0}, {"for", 0}, {"if", 0}, {"int", 0}, {"long", 0}, {"register", 0}, {"return", 0}, {"short", 0}, {"static", 0}, {"struct", 0}, {"switch", 0}, {"typedef", 0}, {"union", 0}, {"unsigned", 0}, {"void", 0}, {"while", 0} }; int GetWord(FILE *fp, char *temp); int BSearch(char *word); void ShowResult(void); void main(void); int GetWord(FILE *fp, char *temp) { int c; int n = 0; while ((c =while ((c = getc(fp)) != EOF) { if (!n && !isalpha(c)) continue; else if (n && !isalpha(c)) { temp[n] = '\0'; return (n); } else if (isalpha(c)) { temp[n] = (char)c; n++; } } return (0); } int BSearch(char *word) { int left = 0; int right = NUM_KW - 1; int mid; int x; while (left <= right) { mid = left + (right - left) / 2; x = strcmp(keyword[mid].name, word); if (x > 0) right = mid -1; else if (x < 0) left = mid + 1; else { keyword[mid].count += 1; return (mid); } } return (-1); } void ShowResult(void) { int i; for (i = 0; i < NUM_KW ; i++) { printf("%10s %3d ", keyword[i].name, keyword[i].count); if (!((i + 1) % 4)) printf("\n"); } } void main(void) { FILE *fp; char word[100]; if ((fp = fopen("wtest.c", "r")) == NULL) { fprintf(stderr, "Can't Open C Source File!\n"); exit(2); } while (GetWord(fp, word)) { BSearch(word) ; } ShowResult( ) ; fclose(fp); }