10
Compter les mots réservés du C dans un fichier
- #include <stdio.h>
- #include <ctype.h>
- #include <string.h>
- #include <stdlib.h>
- #define BSEARCH 1
- typedef struct {
- char *word;
- unsigned count;
- } keyword;
- keyword keytab[] = {
- "auto", 0,
- "break", 0,
- "case", 0,
- "char", 0,
- "const", 0,
- "continue", 0,
- "default", 0,
- "do", 0,
- "double", 0,
- "else", 0,
- "enum", 0,
- "extern", 0,
- "float", 0,
- "for", 0,
- "goto", 0,
- "if", 0,
- "int", 0,
- "long", 0,
- "register", 0,
- "return", 0,
- "short", 0,
- "signed", 0,
- "sizeof", 0,
- "static", 0,
- "struct", 0,
- "switch", 0,
- "typedef", 0,
- "union", 0,
- "unsigned", 0,
- "void", 0,
- "volatile", 0,
- "while", 0
- };
- #define NKEYS (sizeof (keytab)/sizeof (keyword))
- int fgetword( FILE *in, char *word, int mlen ) {
- char *w = word;
- int c;
- while ( (c = getc( in )) != EOF && !isalpha( c ) ) {
- /* skip comments */
- /* skip strings */
- if ( c == '\"' )
- while ( (c = getc( in )) != EOF && c != '\"' )
- ;
- }
- if ( c == EOF )
- return EOF;
- *w++ = c;
- while ( --mlen > 0 ) {
- c = getc( in );
- if ( !isalpha( c ) ) {
- ungetc( c, in );
- break;
- }
- *w++ = c;
- }
- *w = '\0';
- #if defined(DEBUG)
- printf( "%s\n", word );
- #endif
- return 0;
- }
- #if !BSEARCH
- keyword *ksearch( char *w, keyword *tab, int siz ) {
- keyword *l = tab;
- keyword *r = tab+siz;
- keyword *i;
- int cond;
- while ( l < r ) {
- i = l + (r-l) / 2;
- cond = strcmp( w, i->word );
- if ( cond < 0 )
- r = i;
- else if ( cond > 0 )
- l = i + 1;
- else
- return i;
- }
- return 0;
- }
- #endif
- #if BSEARCH
- int keycmp( const char *s, const keyword *k ) {
- return strcmp( s, k->word );
- }
- #endif
- int main() {
- char buf[ 128 ];
- keyword *p;
- while ( fgetword( stdin, buf, sizeof (buf) ) != EOF )
- #if !BSEARCH
- if ( (p = ksearch( buf, keytab, NKEYS)) != 0 )
- #else
- if ( (p = bsearch( buf, keytab, NKEYS, sizeof( keyword ), keycmp )) != 0 )
- #endif
- p->count++;
- for ( p = keytab; p < keytab+NKEYS; p++ )
- if ( p->count > 0 )
- printf( "%d\t%s\n", p->count, p->word );
- exit( 0);
- }
$ gcc -o ckw ckw.c
$ ./ckw < ckw.c
1 break
6 char
2 const
3 else
1 for
12 if
7 int
5 return
4 sizeof
1 struct
1 typedef
1 unsigned
4 while
Commentaires