#include <stdio.h>
struct Key {
char *keyword;
int keycount;
} Keytab[ ] = {
"auto", 0,
"break", 0,
"case", 0,
...
"while", 0
};
#define
#define
#define
#define
struct Key *binary(char *word, struct Key tab[ ], int n);
char getword(char *w, int lim);
char type( int c);
void printKey(struct Key tab[ ], int n);
int main( ) /* count C keyword */
{
int t;
char word[MAXWORD];
struct Key *p;
while((t = getword(word, MAXWORD)) != EOF)
if( t = = LETTER)
if(( p = binary(word, Keytab, NKEYS)) != NULL)
p->keycount++;
printKey(keytab, NKEYS);
return 0;
}
struct Key *binary(char *word, struct Key tab[ ], int n)
{
int cond;
struct Key *low = &tab[0];
struct Key *high = &tab[n-1];
struct Key *mid;
while(low <= high){
mid = low + (high – low) / 2;
if((cond = strcmp(word, mid->keyword)) < 0)
high = mid – 1;
else if ( cond > 0)
low = mid + 1;
else
return (mid);
}
return (NULL);
}
char getword(char *w, int lim)
{
int c, t;
if(type(c = *w++ = getchar( )) != LETTER){
*w = '\0';
return ( c);
}
while(--lim > 0) {
t = type(c = *w++ = getchar( ));
if( t != LETTER && t != DIGIT){
ungetc(c,stdin);
break;
}
}
*(w-1) = '\0';
return ( LETTER);
}
char type(int c) /* return type of ASCII character */
{
if( c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z')
return ( LETTER );
else if ( c >= '0' && c <= '9')
return ( DIGIT );
else return (c);
}
void printKey(struct Key tab[ ], int n)
{
struct Key *p;
for(p=Keytab, p < Keytab+n; p++)
if(p->keycount > 0)
printf("%4d%s\n", p->keycount, p->keyword);
}