Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <string.h>
- #include <locale.h>
- #include <stdlib.h>
- #define HASHSIZE 100
- struct nlist{
- struct nlist *next;
- unsigned int count;
- char *name;
- };
- static struct nlist *hashtab[HASHSIZE];
- struct nlist *lookup(char *s);
- struct nlist *install(char *s);
- void print_hashtab(struct nlist *hashtab[HASHSIZE]);
- unsigned hash(char *s);
- int main(int argc,char *argv[])
- {
- FILE *mf;
- char tmp[50];
- struct nlist *new_word;
- if(argc != 2){printf ("Input an argument"); exit(0);}
- if((mf=fopen(argv[1], "r"))==NULL) printf("Error while opening file\n");
- while(!feof(mf)){
- fscanf(mf,"%s", tmp);
- if((new_word=lookup(tmp))==NULL){
- install(tmp);
- }
- else{
- printf("World %s already in table %d \n", new_word->name, new_word->count);
- }
- }
- print_hashtab(hashtab);
- return 0;
- }
- struct nlist *lookup(char *s){
- struct nlist *np;
- for(np=hashtab[hash(s)]; np != NULL; np=np->next){
- if (strcmp(s, np->name) == 0){
- (np->count)++;
- return np;
- }
- }
- return NULL;
- }
- unsigned hash(char *s){
- unsigned hashval;
- for (hashval = 0; *s != '\0'; s++)
- hashval = *s + 31 * hashval;
- return hashval % HASHSIZE;
- }
- struct nlist *install(char *s){
- struct nlist *np;
- unsigned hashval;
- np=(struct nlist*)malloc(sizeof(*np));
- if (np == NULL || (np->name = strdup(s)) == NULL) return NULL;
- np->count=1;
- hashval=hash(s);
- np->next = hashtab[hashval];
- hashtab[hashval] = np;
- return np;
- }
- void print_hashtab(struct nlist *hashtab[HASHSIZE]){
- for (int i=0; i<HASHSIZE; i++) {
- if(hashtab[i]){
- printf("Word: %s Amount: %d \n", hashtab[i]->name, hashtab[i]->count);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment