Advertisement
dtung

dup.c

Apr 30th, 2020
410
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.47 KB | None | 0 0
  1. #define _GNU_SOURCE
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <stdlib.h>
  5. #include <search.h>
  6.  
  7. #define HASH_SIZE 1000
  8. #define LINE_SIZE 512
  9.  
  10. /* free dynamic allocated entry */
  11. void free_entry(ENTRY *e) {
  12.     if (e == NULL) return;
  13.     free(e->key);
  14. }
  15.  
  16. int main() {
  17.     int hcount = 0;
  18.     char key[LINE_SIZE];
  19.     ENTRY map[HASH_SIZE];
  20.     int data[HASH_SIZE];
  21.     struct hsearch_data htab = {};
  22.  
  23.     /* create hash map */
  24.     hcreate_r(HASH_SIZE, &htab);
  25.     ENTRY *rep;
  26.     /* run through key */
  27.     while (fgets(key, LINE_SIZE, stdin) > 0) {
  28.         /* construct entry */
  29.         data[hcount] = 1;
  30.         ENTRY e = {.key = strdup(key), .data = &data[hcount]};
  31.         /* test existence of entry */
  32.         if (hsearch_r(e, FIND, &rep, &htab)) {
  33.             /* update data */
  34.             int *cp = rep->data;
  35.             (*cp)++;
  36.             free_entry(&e);
  37.         } else {
  38.             /* enter entry */
  39.             if (hsearch_r(e, ENTER, &rep, &htab) && hcount < HASH_SIZE) {  
  40.                 map[hcount++] = e;
  41.             } else {
  42.                 fprintf(stderr, "increase HASH_SIZE\n");
  43.                 exit(1);
  44.             }
  45.         }
  46.     }
  47.  
  48.     /* print hash */
  49.     for (int i = 0; i < hcount; i++) {
  50.         int *cp = map[i].data;
  51.         if (*cp > 1)
  52.             printf("%3d %s", *cp, map[i].key);
  53.     }
  54.     /* free entries */
  55.     for (int i = 0; i < hcount; i++)
  56.         free_entry(&map[i]);
  57.  
  58.     hdestroy_r(&htab);
  59.     exit(0);
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement