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>
- #include <errno.h>
- #define HASH_SIZE 1000
- #define LINE_SIZE 512
- /* define client data */
- typedef struct client {
- int count;
- } CLIENT;
- /* duplicate client data */
- CLIENT *datadup(CLIENT *data) {
- CLIENT *r = malloc(sizeof(CLIENT));
- if (r == NULL) return NULL;
- *r = *data;
- return r;
- }
- /* free dynamic allocated entry */
- void free_entry(ENTRY *e) {
- if (e == NULL) return;
- free(e->key);
- free(e->data);
- }
- int main() {
- int hindex = 0;
- char key[LINE_SIZE];
- ENTRY map[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 */
- CLIENT data = {.count = 1};
- ENTRY e = {.key = strdup(key), .data = datadup(&data)};
- /* check entry */
- if (hsearch_r(e, FIND, &rep, &htab)) {
- /* update data */
- if (rep != NULL) {
- CLIENT *cp = rep->data;
- cp->count++;
- }
- free_entry(&e);
- } else {
- /* enter entry */
- if (hsearch_r(e, ENTER, &rep, &htab) && hindex < HASH_SIZE) {
- map[hindex++] = e;
- } else {
- fprintf(stderr, "increase HASH_SIZE: %s\n", strerror(errno));
- exit(1);
- }
- }
- }
- /* print hash */
- for (int i = 0; i < hindex; i++) {
- CLIENT *cp = map[i].data;
- if (cp->count > 1)
- printf("%3d %s", cp->count, map[i].key);
- }
- /* free entries */
- for (int i = 0; i < hindex; i++)
- free_entry(&map[i]);
- hdestroy_r(&htab);
- exit(0);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement