Category : C Source Code
Archive   : QC_K_R.ZIP
Filename : EX6_01.C

 
Output of file : EX6_01.C contained in archive : QC_K_R.ZIP
/* exercise 6-1, page 128 */

#include
#define MAXWORD 20
#define LETTER 'a'
#define DIGIT '0'
#define NKEYS sizeof(keytab) / sizeof(struct key)
struct key {
char *keyword;
int keycount;
} keytab[] ={
"auto",0,
"break", 0,
"case", 0,
"char", 0,
"continue", 0,
"default", 0,
"do", 0,
"double", 0,
"else", 0,
"entry", 0,
"extern", 0,
"float", 0,
"for", 0,
"goto", 0,
"if", 0,
"int", 0,
"long", 0,
"register", 0,
"return", 0,
"short", 0,
"sizeof", 0,
"static", 0,
"struct", 0,
"switch", 0,
"typedef", 0,
"union", 0,
"unsigned", 0,
"while", 0,
};

main() /* count C keywords */
{
int n, t;
char word[MAXWORD];

while ((t = getword(word, MAXWORD)) != EOF)
if (t == LETTER)
if ((n = binary(word, keytab, NKEYS)) >= 0)
keytab[n].keycount++;
for (n = 0; n < NKEYS; n++)
if (keytab[n].keycount > 0)
printf("%4d %s\n",
keytab[n].keycount, keytab[n].keyword);
}

binary(word, tab, n) /* find word in tab[0]...tab[n-1] */
char *word;
struct key tab[];
int n;
{
int low, high, mid, cond;

low = 0;
high = n - 1;
while (low <= high) {
mid = (low+high) / 2;
if ((cond = strcmp(word, tab[mid].keyword)) < 0)
high = mid - 1;
else if (cond > 0)
low = mid + 1;
else
return(mid);
}
return(-1);
}
static char type[] ={ 0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,'0','0',
'0','0','0','0','0','0','0','0',0,0,
0,0,0,0,0,'a','a','a','a','a',
'a','a','a','a','a','a','a','a','a','a',
'a','a','a','a','a','a','a','a','a','a',
'a',0,0,0,0,0,0,'a','a','a',
'a','a','a','a','a','a','a','a','a','a',
'a','a','a','a','a','a','a','a','a','a',
'a','a','a',0,0,0,0,0 };

getword(w, lim) /* get next word from input */
char *w;
int lim;
{
int c, t;


if (type[*w++ = c = getch()] != LETTER) {
*w = '\0';
return(c);
}
while (--lim > 0) {
t = type[*w++ = c = getch()];
if (t != LETTER && t != DIGIT) {
ungetch(c);
break;
}
}
*(w-1) = '\0';
return(LETTER);
}

int buf[1]; /* buffer for ungetch */
int bufp = 0; /* next free position in buf */

getch() /* get a (possibly pushed back) character */
{
return((bufp == 1) ? buf[--bufp] : getchar());
}

ungetch(c) /* push character back on input */
int c;
{
buf[bufp++] = c;
}



  3 Responses to “Category : C Source Code
Archive   : QC_K_R.ZIP
Filename : EX6_01.C

  1. Very nice! Thank you for this wonderful archive. I wonder why I found it only now. Long live the BBS file archives!

  2. This is so awesome! 😀 I’d be cool if you could download an entire archive of this at once, though.

  3. But one thing that puzzles me is the “mtswslnkmcjklsdlsbdmMICROSOFT” string. There is an article about it here. It is definitely worth a read: http://www.os2museum.com/wp/mtswslnk/