home *** CD-ROM | disk | FTP | other *** search
/ Serving the Web / ServingTheWeb1995.disc1of1.iso / linux / slacksrce / d / libc / libc-4.6 / libc-4 / libc-linux / misc / ttest.c < prev    next >
Encoding:
C/C++ Source or Header  |  1994-08-20  |  1.7 KB  |  71 lines

  1. #include <stdio.h>
  2. #include <search.h>
  3.  
  4. struct node {          /* pointers to these are stored in the tree */
  5.      char *string;
  6.      int count;
  7. };
  8.  
  9. #define MAXNODES    12
  10. #define MAXSTRING   100
  11. #define MINSTRING   3        /* char, newline, eos */
  12. char string_space[MAXSTRING];         /* space to store strings */
  13. struct node node_space[MAXNODES];  /* nodes to store */
  14. struct node *root = NULL;         /* this points to the root */
  15.  
  16. /*
  17.      This routine compares two nodes, based on an
  18.      alphabetical ordering of the string field.
  19. */
  20. int node_compare(node1, node2)
  21.      const struct node *node1, *node2;
  22. {
  23.      return strcmp(node1->string, node2->string);
  24. }
  25.  
  26. /* Print out nodes in alphabetical order */
  27. /*ARGSUSED2*/
  28. void
  29. print_node(node, order, level)
  30.      struct node **node;
  31.      VISIT order;
  32.      int level;
  33. {
  34.      if (order == postorder || order == leaf) {
  35.             (void) printf("string = %20s,  count = %d\n",
  36.             (*node)->string, (*node)->count);
  37.      }
  38. }
  39.  
  40. main()
  41. {
  42.      char *strptr = string_space;
  43.      int maxstrlen = MAXSTRING;
  44.      struct node *nodeptr = node_space;
  45.      struct node **found;
  46.      int length;
  47.  
  48.      while (fgets(strptr, maxstrlen, stdin) != NULL) {
  49.             /* remove the trailing newline */
  50.             length = strlen(strptr);
  51.             strptr[length-1] = 0;
  52.             /* set node */
  53.             nodeptr->string = strptr;
  54.             /* locate node into the tree */
  55.             found = (struct node **)
  56.             tsearch((void *) nodeptr, (void **) &root, node_compare);
  57.             /* bump the count */
  58.             (*found)->count++;
  59.             if (*found == nodeptr) {
  60.              /* node was inserted, so get a new one */
  61.              strptr += length;
  62.              maxstrlen -= length;
  63.              if (maxstrlen < MINSTRING)
  64.                   break;
  65.              if (++nodeptr >= &node_space[MAXNODES])
  66.                   break;
  67.             }
  68.      }
  69.      twalk((char *)root, print_node);
  70. }
  71.