unsigned int bst_c(bst *t, char c) { // base case: empty tree (end of the search) if (t == NULL) { return 0; } // recursive case 1: match found // must go down both branches if (c == t->c->cnet[0]) { printf("%s\n", t->c->cnet); return 1 + bst_c(t->lsub, c) + bst_c(t->rsub, c); } // recursive case 2: no match // go down the correct branch if (c < t->c->cnet[0]) { return bst_c(t->lsub, c); } else if (c > t->c->cnet[0]) { return bst_c(t->rsub, c); } else { fprintf(stderr, "error in bst_c: impossible comparison\n"); exit(1); } }
/* shows all the cnets that start with the given char, * in alphabetical order. returns the count of cnets displayed */ unsigned int bst_c(FILE *f, bst *t, char c) { if(t == NULL) return 0; char* cnet = t -> c -> cnet; int cmp = c - *cnet; if(cmp == 0) { int left = bst_c(f, t -> lsub, c); fprintf(f, "%s\n", cnet); int right = bst_c(f, t -> rsub, c); return 1 + left + right; } if(cmp > 0) return bst_c(f, t -> rsub, c); return bst_c(f, t -> lsub, c); }
/* curr_file pointer must point to a heap-allocated string */ int process_cmd(char **curr_file, char *cmd, bst **address_book, int *quit) { int parse_succeeded; char *cnet; char *infile; char *first_char; switch (cmd[0]) { case 'q': if (strcmp(cmd,"q")==0) { *quit = 1; return 1; } return 0; case 's': if (strcmp(cmd,"s")==0) { if (strlen(*curr_file)>0) fprintf(stdout,"Current file: %s.\n",*curr_file); addr_book_stats(*address_book); return 1; } return 0; case 'r': infile = extract_arg(cmd, &parse_succeeded); if (parse_succeeded) { bst *tmp = *address_book; *address_book = admin_addr_book_from_file(infile); if (*address_book==NULL) { /* restore address book */ *address_book = tmp; } else { free(*curr_file); *curr_file = infile; bst_free(tmp); } } return parse_succeeded; case 'c': first_char = extract_arg(cmd, &parse_succeeded); if (parse_succeeded) { if (strlen(first_char)!=1) fprintf(stdout,"Please type exactly one character as argument to c.\n"); else { unsigned int z = bst_c(*address_book, first_char[0]); printf("(found %u CNETs starting with '%c')\n",z,first_char[0]); } putchar('\n'); free(first_char); } return parse_succeeded; case 'l': cnet = extract_arg(cmd, &parse_succeeded); if (parse_succeeded) { int n_comparisons = 0; vcard *c = bst_search(*address_book, cnet, &n_comparisons); if (c==NULL) fprintf(stdout,"%s not found in current address book.\n", cnet); else vcard_show(c); fprintf(stdout,"(Performed %d comparisons in search.)\n", n_comparisons); putchar('\n'); } free(cnet); return parse_succeeded; case 'h': help_text(); return 1; default: return 0; } }