Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define _GNU_SOURCE
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- #include <search.h>
- #define HASH_SIZE 1000
- #define LINE_SIZE 512
- /* free dynamic allocated entry */
- void free_entry(ENTRY *e) {
- if (e == NULL) return;
- free(e->key);
- }
- int main() {
- int hcount = 0;
- char key[LINE_SIZE];
- ENTRY map[HASH_SIZE];
- int data[HASH_SIZE];
- struct hsearch_data htab = {};
- /* create hash map */
- hcreate_r(HASH_SIZE, &htab);
- ENTRY *rep;
- /* run through key */
- while (fgets(key, LINE_SIZE, stdin) > 0) {
- /* construct entry */
- data[hcount] = 1;
- ENTRY e = {.key = strdup(key), .data = &data[hcount]};
- /* test existence of entry */
- if (hsearch_r(e, FIND, &rep, &htab)) {
- /* update data */
- int *cp = rep->data;
- (*cp)++;
- free_entry(&e);
- } else {
- /* enter entry */
- if (hsearch_r(e, ENTER, &rep, &htab) && hcount < HASH_SIZE) {
- map[hcount++] = e;
- } else {
- fprintf(stderr, "increase HASH_SIZE\n");
- exit(1);
- }
- }
- }
- /* print hash */
- for (int i = 0; i < hcount; i++) {
- int *cp = map[i].data;
- if (*cp > 1)
- printf("%3d %s", *cp, map[i].key);
- }
- /* free entries */
- for (int i = 0; i < hcount; i++)
- free_entry(&map[i]);
- hdestroy_r(&htab);
- exit(0);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement