1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
|
/* 1Lign1Phrase.c inspiré de K&R page145 */
/* 1Lign1Phrase <t.txt >t2.txt & t2.txt */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define HASHSIZE 150
struct nlist {
struct nlist *next;
char *name;
char *defn;
};
static struct nlist *hashtab[HASHSIZE]; /* tableau de pointeurs */
struct nlist *install( char *name, char *defn );
int pstrcmp(const void * p1, const void * p2);
struct nlist *lookup( char *s );
unsigned hash( char *s );
/* ********************* fonctions ********************************* */
struct nlist *lookup( char *s ) {
struct nlist *np;
for ( np = hashtab[hash( s )]; np != NULL; np = np->next )
if ( strcmp( s, np->name ) == 0 )
return np;
return NULL;
}
unsigned hash( char *s )
{
unsigned hashval;
for ( hashval = 0; *s != '\0' ;s++ ) {
hashval = *s + 31 * hashval;
}
return hashval % HASHSIZE;
}
/* FAQ Fonction qui compare deux pointeurs vers des chaines pour qsort */
int pstrcmp(const void * p1, const void * p2)
{
return strcmp(*(char * const *)p1, *(char * const *)p2);
}
struct nlist *install( char *name, char *defn ) {
struct nlist *np;
unsigned hashval;
if ( ( np = lookup( name ) ) == NULL ) { /* not found */
np = ( struct nlist* ) malloc( sizeof( *np ) );
if ( NULL == np || NULL == ( np->name = strdup( name ) ) )
return NULL;
hashval = hash( name );
np->next = hashtab[hashval];
hashtab[hashval] = np;
} else /* already there */
free( ( void* ) np->defn ); /* free previous definiition */
if ( NULL == ( np->defn = strdup( defn ) ) )
return NULL;
/* printf ("%s", np->name); */
return np;
}
/* ************************** MAIN ******************************* */
/* 1Lign1Phrase <t.txt >t2.txt & t2.txt */
int main( void )
{
size_t i;
struct nlist *npp;
int j = 0;
int k = 0;
char basebuf[HASHSIZE] = {0};
char *tableAsort[HASHSIZE] = {0};
while ( NULL != fgets( basebuf, sizeof basebuf, stdin ) )
install(basebuf , "");
for ( i = 0 ; i < HASHSIZE ; i++ )
for ( npp = hashtab[i] ; npp != NULL ; npp = npp->next)
tableAsort[j++] = strdup(npp->name);
qsort (tableAsort, j-1, sizeof (*tableAsort), pstrcmp);
printf ( "\n--------- qsort the hashedbuff ---------------\n\n" );
for (k=0; tableAsort[k] != NULL ; k++)
printf("%s", tableAsort[k] );
fflush(stdout);
return EXIT_SUCCESS;
}/* end main */ |
Partager