X-Git-Url: http://pileus.org/git/?p=~andy%2Fsfvlug;a=blobdiff_plain;f=c%2Fsrc%2Fopts.c;fp=c%2Fsrc%2Fopts.c;h=9fc0ae12fc33fcf0b5bac299967117cb010a3f6b;hp=0000000000000000000000000000000000000000;hb=bc60878f14313f857dedc9954f189f37528386b7;hpb=4d380e0b82a77240bc5859c13161e90128d15f0d diff --git a/c/src/opts.c b/c/src/opts.c new file mode 100644 index 0000000..9fc0ae1 --- /dev/null +++ b/c/src/opts.c @@ -0,0 +1,67 @@ +#include +#include +#include + +/* Options */ +static int opt_verbose = 0; +static char *opt_greeting = "Hello"; +static char *opt_name = "World"; + +/* Parsing */ +static char *short_options = "hvg:n:"; + +static struct option long_options[] = { + {"help", 0, NULL, 'h'}, + {"verbose", 0, NULL, 'v'}, + {"greeting", 1, NULL, 'g'}, + {"name", 1, NULL, 'n'}, +}; + +/* Show usage information */ +static void usage(int status) +{ + printf("opts -[OPTIONS]\n"); + printf("\n"); + printf("Options:\n"); + printf(" -h,--help Show usage information\n"); + printf(" -v,--verbose Print debug output messages\n"); + printf(" -n,--greeting=STR Use the given greeting\n"); + printf(" -n,--name=NAME Greet the given person\n"); + exit(status); +} + +/* Parse command line arguments */ +static void parse(int argc, char **argv) +{ + while (1) { + int c = getopt_long(argc, argv, + short_options, long_options, 0); + if (c == -1) + break; + switch (c) { + case 'h': usage(0); break; + case 'v': opt_verbose = 1; break; + case 'g': opt_greeting = optarg; break; + case 'n': opt_name = optarg; break; + default: usage(1); break; + } + } + if (argc != optind) + usage(1); + + if (opt_verbose) { + printf("Options:\n"); + printf(" verbose = %d\n", opt_verbose); + printf(" greeting = %s\n", opt_greeting); + printf(" name = %s\n", opt_name); + printf("\n"); + } +} + +/* Main entry point */ +int main(int argc, char **argv) +{ + parse(argc, argv); + printf("%s, %s\n", opt_greeting, opt_name); + return 0; +}