Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdlib.h>
- #include <stdio.h>
- #include <getopt.h>
- #include "mylib.h"
- #include "tree.h"
- /* A boolean type which can be TRUE or FALSE */
- typedef enum bool_e {FALSE, TRUE} bool_t;
- static void usage(char *progname);
- static void setup(int argc, char **argv, char **filename, bool_t *rbt,
- bool_t *do_depth, bool_t *p_order, bool_t *output_graph);
- static void make_graph(char *filename, tree t);
- static void usage(char *prog_name) {
- fprintf(stderr, "Usage: %s [OPTION]... <STDIN>nn%s%s", prog_name,
- "Perform various operations using a hash-table. By default readn"
- "words from stdin and print them with their frequencies to stdout.nn"
- " -d prints the tree depthn"
- " -p prints the tree in pre_ordern"
- " -o FILENAME prints output to a specified filenn"
- " -r creates a rbt treen"
- " -h Display this messagenn");
- }
- static void print_key(char *key) {
- printf("%sn", key);
- }
- static void make_graph(char *filename, tree t) {
- FILE *file = fopen(filename, "w");
- fprintf(stderr, "Creating dot file '%s'n", filename);
- tree_output_dot(t, file);
- fclose(file);
- }
- /**
- * Handle options given on the command-line by setting a number of
- * variables appropriately. May call usage() if incorrect arguments
- * or -h given.
- *
- * @param argc the number of command-line arguments.
- * @param argv an array of strings contain the command-line arguments.
- * @param rbt is created if -r is given
- * @param the tree depth is printed if d is given
- * @param tree_outputfile_dot is called if -o output-filename is given
- */
- int main(int argc, char **argv) {
- bool_t rbt = FALSE, do_depth = FALSE, p_order = FALSE, output_graph = FALSE;
- tree_t tree_type = BST;
- tree t;
- char word[256];
- char *dot_filename;
- setup(argc, argv, &dot_filename, &rbt, &do_depth, &p_order, &output_graph);
- if (rbt) {
- t = tree_new(RBT);
- } else {
- t = tree_new(tree_type);
- }
- while ((getword(word, sizeof word, stdin)) != EOF) {
- t = tree_insert(t, word);
- }
- if (do_depth) {
- printf("%dn", tree_depth(t));
- } else if (p_order) {
- tree_preorder(t, print_key);
- } else if (output_graph) {
- make_graph(dot_filename, t);
- } else {
- tree_inorder(t, print_key);
- }
- t = tree_free(t);
- return EXIT_SUCCESS;
- }
- static void setup(int argc, char **argv, char **filename, bool_t *rbt,
- bool_t *do_depth, bool_t *p_order, bool_t *output_graph) {
- const char *optstring = "do:prh";
- char option;
- while ((option = getopt(argc, argv, optstring)) != EOF) {
- switch (option) {
- case 'd':
- *do_depth = TRUE;
- break;
- case 'o':
- *filename = optarg;
- *output_graph = TRUE;
- break;
- case 'p':
- *p_order = TRUE;
- break;
- case 'r':
- *rbt = TRUE;
- break;
- case 'h':
- default:
- usage(argv[0]);
- exit(EXIT_SUCCESS);
- }
- }
- }
- char *dot_filename = NULL;
Add Comment
Please, Sign In to add comment