HP-UX Reference (11i v3 07/02) - 3 Library Functions N-Z (vol 7)

t
tsearch(3C) tsearch(3C)
EXAMPLES
The following code reads strings, and stores structures containing a pointer to each string and a count of its
length. It then walks the tree, printing out the stored strings and their lengths in alphabetical order.
#include <stdlib.h>
#include <search.h>
#include <stdio.h>
#include <string.h>
struct element /* pointers to these are stored in the tree */
{
char *string;
int length;
};
char string_space[10000]; /* space to store strings */
struct element elements[500]; /* elements to store */
struct element *root = NULL; /* this points to the root */
void print_node(void *, VISIT, int);
int element_compare(const void *, const void *);
main( )
{
char *strptr = string_space;
struct element *element_ptr = elements;
struct element **ts_retval;
int i = 0;
while (gets(strptr) != NULL && i++ < 500)
{
/* set element */
element_ptr->string = strptr;
element_ptr->length = strlen(strptr);
/* put element into the tree */
ts_retval = (struct element **) tsearch((void *) element_ptr,
(void **) &root, element_compare);
if (*ts_retval == element_ptr)
{
(void) printf("The element \"%s\" ",
(*ts_retval)->string);
(void) printf("has now been inserted into the tree\n");
}
else
{
(void) printf("The element \"%s\" ",
(*ts_retval)->string);
(void) printf("already existed in the tree\n");
}
/* adjust pointers, so we don’t overwrite tree */
strptr += element_ptr->length + 1;
element_ptr++;
}
twalk((void *) root, print_node);
}
/* This routine compares two elements, based on an
alphabetical ordering of the string field. */
int
element_compare(elem1, elem2)
void *elem1, *elem2;
{
return strcmp(((struct element *) elem1)->string,
((struct element *) elem2)->string);
}
HP-UX 11i Version 3: February 2007 2 Hewlett-Packard Company 577