|
NAMEhcreate , hcreate_r ,
hdestroy , hdestroy_r ,
hsearch , hsearch_r —
manage hash search table
LIBRARYStandard C Library (libc, -lc)SYNOPSIS#include <search.h>
int
int
void
void
ENTRY *
int
DESCRIPTIONThehcreate (), hcreate_r (),
hdestroy (), hdestroy_r ()
hsearch (), and hsearch_r ()
functions manage hash search tables.
The The The The comparison key (passed to The RETURN VALUESThehcreate () and hcreate_r ()
functions return 0 if the table creation failed and the global variable
errno is set to indicate the error; otherwise, a
non-zero value is returned.
The The EXAMPLESThe following example reads in strings followed by two numbers and stores them in a hash table, discarding duplicates. It then reads in strings and finds the matching entry in the hash table and prints it out.#include <stdio.h> #include <search.h> #include <string.h> #include <stdlib.h> struct info { /* This is the info stored in the table */ int age, room; /* other than the key. */ }; #define NUM_EMPL 5000 /* # of elements in search table. */ int main(void) { char str[BUFSIZ]; /* Space to read string */ struct info info_space[NUM_EMPL]; /* Space to store employee info. */ struct info *info_ptr = info_space; /* Next space in info_space. */ ENTRY item; ENTRY *found_item; /* Name to look for in table. */ char name_to_find[30]; int i = 0; /* Create table; no error checking is performed. */ (void) hcreate(NUM_EMPL); while (scanf("%s%d%d", str, &info_ptr->age, &info_ptr->room) != EOF && i++ < NUM_EMPL) { /* Put information in structure, and structure in item. */ item.key = strdup(str); item.data = info_ptr; info_ptr++; /* Put item into table. */ (void) hsearch(item, ENTER); } /* Access table. */ item.key = name_to_find; while (scanf("%s", item.key) != EOF) { if ((found_item = hsearch(item, FIND)) != NULL) { /* If item is in the table. */ (void)printf("found %s, age = %d, room = %d\n", found_item->key, ((struct info *)found_item->data)->age, ((struct info *)found_item->data)->room); } else (void)printf("no such employee %s\n", name_to_find); } hdestroy(); return 0; } ERRORSThehcreate (), hcreate_r (),
hsearch (), and hsearch_r ()
functions will fail if:
The
SEE ALSObsearch(3), lsearch(3), malloc(3), strcmp(3), tsearch(3)STANDARDSThehcreate (), hdestroy (), and
hsearch () functions conform to X/Open
Portability Guide Issue 4, Version 2
(“XPG4.2”).
HISTORYThehcreate (), hdestroy (), and
hsearch () functions first appeared in
AT&T System V UNIX. The
hcreate_r (), hdestroy_r () and
hsearch_r () functions are GNU extensions.
BUGSThe original, non-GNU interface permits the use of only one hash table at a time.
Visit the GSP FreeBSD Man Page Interface. |