HP-UX Reference (11i v1 00/12) - 3 Library Functions N-Z (vol 7)
__________________________________________________________________________________________________________________________________________________________________________________________________
__________________________________________________________________________________________________________________________________________________________________________________________________
STANDARD Printed by: Nora Chuang [nchuang] STANDARD
/build/1111/BRICK/man3/nan.3m
________________________________________________________________
___ ___
t
tsearch(3C) tsearch(3C)
APPLICATION USAGE
tsearch(), tfind(), tdelete() and twalk() are thread-safe. These interfaces are not async-
cancel-safe.
EXAMPLE
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 alphabeticalorder.
#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;
Section 3−−988 − 2 − HP-UX Release 11i: December 2000
___
___