/* mysortu2.c Jim Plank 7 February, 1994 */ /* This program is just like mysortu1.c, except that it prints out the number of times a particular line occurred, in addition to sorting them. This is effected by storing a count as the "val" field in each rb_node. Note that you cast the (int *) to a (char *). This is legal and safe in C because all pointers are the same size. */ #include #include #include "fields.h" #include "rb.h" #define talloc(type, size) (type *) malloc(sizeof(type)*(size)) main() { IS is; char *copy; Rb_node sorted_lines, tmp, r; int found; int *count; sorted_lines = make_rb(); is = new_inputstruct(NULL); while(get_line(is) >= 0) { r = rb_find_key_n(sorted_lines, is->text1, &found); /* If the line is already in the tree, then just increment its count */ if (found) { count = (int *) r->v.val; *count = *count + 1; /* Otherwise, insert the line into the tree with a count of one */ } else { count = talloc(int, 1); *count = 1; copy = strdup(is->text1); rb_insert(sorted_lines, copy, (char *)count); } } rb_traverse(tmp, sorted_lines) { count = (int *) tmp->v.val; printf("%6d\t%s", *count, tmp->k.key); } }