10rch

Untitled

Jun 8th, 2017
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.88 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <locale.h>
  4. #include <stdlib.h>
  5. #define HASHSIZE 100
  6.  
  7.  
  8. struct nlist{
  9.     struct nlist *next;
  10.     unsigned int count;
  11.     char *name;
  12. };
  13. static struct nlist *hashtab[HASHSIZE];
  14. struct nlist *lookup(char *s);
  15. struct nlist *install(char *s);
  16. void print_hashtab(struct nlist *hashtab[HASHSIZE]);
  17. unsigned hash(char *s);
  18.  
  19. int main(int argc,char *argv[])
  20. {
  21.  
  22.     FILE *mf;
  23.     char tmp[50];
  24.     struct nlist *new_word;
  25.     if(argc != 2){printf ("Input an argument"); exit(0);}
  26.         if((mf=fopen(argv[1], "r"))==NULL) printf("Error while opening file\n");
  27.         while(!feof(mf)){
  28.             fscanf(mf,"%s", tmp);
  29.             if((new_word=lookup(tmp))==NULL){
  30.                 install(tmp);
  31.             }
  32.             else{
  33.                 printf("World %s already in table %d \n", new_word->name, new_word->count);
  34.             }
  35.         }
  36.         print_hashtab(hashtab);
  37.  
  38.     return 0;
  39. }
  40.  
  41. struct nlist *lookup(char *s){
  42.     struct nlist *np;
  43.     for(np=hashtab[hash(s)]; np != NULL; np=np->next){
  44.         if (strcmp(s, np->name) == 0){
  45.             (np->count)++;
  46.             return np;
  47.         }
  48.     }
  49.     return NULL;
  50. }
  51.  
  52. unsigned hash(char *s){
  53.     unsigned hashval;
  54.     for (hashval = 0; *s != '\0'; s++)
  55.         hashval = *s + 31 * hashval;
  56.     return hashval % HASHSIZE;
  57. }
  58.  
  59. struct nlist *install(char *s){
  60.     struct nlist *np;
  61.     unsigned hashval;
  62.     np=(struct nlist*)malloc(sizeof(*np));
  63.     if (np == NULL || (np->name = strdup(s)) == NULL) return NULL;
  64.     np->count=1;
  65.     hashval=hash(s);
  66.     np->next = hashtab[hashval];
  67.     hashtab[hashval] = np;
  68.     return np;
  69. }
  70.  
  71. void print_hashtab(struct nlist *hashtab[HASHSIZE]){
  72.     for (int i=0; i<HASHSIZE; i++) {
  73.         if(hashtab[i]){
  74.             printf("Word: %s   Amount: %d \n", hashtab[i]->name, hashtab[i]->count);
  75.         }
  76.     }
  77. }
Advertisement
Add Comment
Please, Sign In to add comment