Code:
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define MAXWORD 100
#define NKEYS (sizeof keytab / sizeof (struct key))
#define BUFSIZE 100
struct key {
char *word;
int count;
} keytab[] = {
/* "auto", 0, "break", 0, "case", 0, "char", 0, "const", 0, "continue", 0, "default", 0, "unsigned", 0, "void", 0, "volatile", 0, "while", 0, "if", 0, "for", 0, "return", 0, "define", 0,*/
{"a3a^", 0}, {"b", 0}, {"c", 0}, {"d", 0}, {"e", 0}, {"f", 0}, {"g", 0}, {"h", 0}, {"i", 0}, {"j", 0}, {"k", 0}, {"l", 0}, {"m", 0}, {"n", 0}, {"o", 0}, {"p", 0}, {"q", 0}, {"r", 0}, {"s", 0}, {"t", 0}, {"u", 0}, {"v", 0}, {"w", 0}, {"x", 0}, {"y", 0}, {"z", 0}};
int getword(char *, int);
int binsearch(char *, struct key *, int);
char buf[BUFSIZE]; /* buffer for ungetch */
int bufp = 0; /* next free position in buf */
/* count C keywords */
int main()
{
int n;
char word[MAXWORD];
while (getword(word, MAXWORD) != EOF) {
if (isalpha(word[0])) {
if ((n = binsearch(word, keytab, NKEYS)) >= 0) {
keytab[n].count++;
}
}
}
for (n = 0; n < NKEYS; n++) {
if (keytab[n].count > 0) {
printf("%4d %s\n", keytab[n].count, keytab[n].word);
}
}
return 0;
}
int binsearch(char *word, struct key tab[], int n)
{
int cond;
int low, high, mid;
low = 0;
high = n - 1;
while( low <= high) {
mid = (low+high) / 2;
if ((cond = strcmp(word, tab[mid].word)) < 0) {
high = mid - 1;
} else if (cond > 0) {
low = mid + 1;
} else {
return mid;
}
}
return -1;
}
int getword( char *word, int lim)
{
int c, getch(void);
void ungetch(int);
char *w;
w = word;
c = getch();
if(isspace(c)) {
;
}
if(c != EOF) {
*w++ = c;
}
if(!isalpha(c)) {
*w = '\0';
return c;
}
for ( ; --lim > 0; w++) {
if (!isalnum(*w = getch())) {
ungetch(*w);
break;
}
}
*w = '\0';
return word[0];
}
int getch(void) /* get a (possibly pushed back) character */
{
return (bufp > 0) ? buf[--bufp] : getchar();
}
void ungetch(int c) /* push character back on input */
{
if(bufp >= BUFSIZE) {
printf("ungetch: too many characters\n");
} else {
buf[bufp++] = c;
}
}
In the above code, the function