From: Colin P. Mccabe Date: Thu, 20 Dec 2018 21:48:09 +0000 (-0800) Subject: Some improvements to random_word X-Git-Url: http://www.club.cc.cmu.edu/~cmccabe/cgi-bin/gitweb.cgi?p=cmccabe-bin;a=commitdiff_plain;h=0199f6555377ad9d2bc9fc40f3c3df2c081d2f57 Some improvements to random_word * Change name from random-word to random_word. * Make the path to the dictionary configurable. * Add random_word to the Makefile. --- diff --git a/.gitignore b/.gitignore index 74827ca..da93917 100644 --- a/.gitignore +++ b/.gitignore @@ -15,6 +15,7 @@ hexconv msgpack-translate directory_merge pickrand +random_word audiobooker # diff --git a/Makefile b/Makefile index a5aeef5..db04831 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ CFLAGS=-Wall -O2 -all: audiobooker bytor errno_speak show_default_sockopts simple_time vimstart hexconv +all: audiobooker bytor errno_speak show_default_sockopts random_word simple_time vimstart hexconv audiobooker: go build audiobooker.go @@ -18,5 +18,7 @@ vimstart: vimstart.o hexconv: hexconv.o +random_word: random_word.o + clean: rm -rf bytor errno_speak show_default_sockopts simple_time vimstart hexconv *.o diff --git a/random-word.c b/random_word.c similarity index 69% rename from random-word.c rename to random_word.c index d751d06..f29bc7d 100644 --- a/random-word.c +++ b/random_word.c @@ -3,8 +3,9 @@ #include #include #include +#include -#define DICT "/usr/share/dict/linux.words" +#define DEFAULT_DICT_PATH "/usr/share/dict/linux.words" #define STARTING_SZ 8192 #define MAX_ARRAY_SZ 1073741824 @@ -86,21 +87,54 @@ static const char* choose_random_word(struct dict *dict) return dict->words[choice]; } -int main(void) +static void print_usage(char *program_name) +{ + printf("%s: prints a random word from a linebreak-delimited file.\n", + program_name); + printf("options:\n"); + printf("\t-d: the dictionary file to use. Default: %s.\n", + DEFAULT_DICT_PATH); + printf("\t-h: this help message.\n"); +} + +static void parse_args(char **argv, int argc, char **dict_path) +{ + char c; + *dict_path = DEFAULT_DICT_PATH; + opterr = 0; + while ((c = getopt(argc, argv, "d:h")) != -1) { + switch (c) { + case 'd': + *dict_path = optarg; + break; + case 'h': + print_usage(argv[0]); + exit(0); + break; + default: + fprintf (stderr, "Argument parsing error.\n"); + exit(1); + } + } +} + +int main(int argc, char **argv) { FILE *fp; + char *dict_path; const char *word; struct dict *dict; struct timeval tv; + parse_args(argv, argc, &dict_path); gettimeofday(&tv, NULL); srandom(tv.tv_usec * tv.tv_sec); - fp = fopen(DICT, "r"); + fp = fopen(dict_path, "r"); if (! fp) { int err = errno; fprintf(stderr, "failed to open %s: %s (%d).\n", - DICT, strerror(err), err); + dict_path, strerror(err), err); return 1; } dict = read_dict(fp);