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
| typedef struct L {
char *str;
struct L *next;
}list;
char *readData( FILE *doc) {
char chaine[ARRAY_SIZE];
char *p = NULL;
if (doc != NULL && fgets(chaine,ARRAY_SIZE, doc)!= NULL)
{
p = strchr(chaine, ' ');
if(p!= NULL) *p = '\0';
p = malloc(strlen(chaine)+1);
if(p != NULL) strcpy(p, chaine);
}
return p;
}
unsigned long hash(char *key) {
unsigned long h = 0;
int c;
for(; *key; key++)
h = h + *key;
return h % TABLE_SIZE;
}
void insertHash(list **h_table, char *mot) {
h_table = (list **)malloc(TABLE_SIZE * sizeof(list*));
unsigned long val = hash(mot);
list *my_list = h_table[val];
if(my_list != NULL)
{
strcpy(mot, my_list->str);
my_list->next = h_table[val];
h_table[val] = my_list;
}
}
list *retrieveHash (list **my_table, char *word) {
list *a_list;
unsigned long key = hash(word);
for (a_list = my_table[key]; a_list != NULL; a_list = a_list->next) {
if(strcmp(word, a_list->str) == 0)
return a_list;
}
return NULL;
}
int main( int argc, char *argv[]) {
FILE *fichier = NULL;
list **table = NULL;
list *liste;
char *buff;
int i = 0;
if (argc>1)
{
fichier = fopen(argv[1], "r");
}
do{
buff= readData(fichier);
if (buff != NULL)
insertHash(table, buff);
} while (buff != NULL);
liste = retrieveHash(table,"years");
while(liste) {
if (liste == NULL)
printf("occurence = 0");
else
i++;
liste = liste->next;
}
printf("occurence = %d", i);
return 0;
} |
Partager