diff --git a/digressions/getopt-example.c b/digressions/getopt-example.c index 2401c4b..1b469c0 100644 --- a/digressions/getopt-example.c +++ b/digressions/getopt-example.c @@ -4,17 +4,29 @@ #include #include #include +#include -int -main(int argc, char *argv[]) -{ + +void die_usage(char *prog, char *msg) { + fprintf(stderr, "Usage: %s [-t nsecs] [-n] name\n", prog); + if (msg != NULL) { + fprintf(stderr, "%s\n", msg); + } + exit(EXIT_FAILURE); +} + + +int main(int argc, char *argv[]) { + char *prog; int flags, opt; int nsecs, tfnd; nsecs = 0; tfnd = 0; flags = 0; - while ((opt = getopt(argc, argv, "nt:")) != -1) { + prog = basename(argv[0]); + + while ((opt = getopt(argc, argv, "hnt:")) != -1) { switch (opt) { case 'n': flags = 1; @@ -23,23 +35,20 @@ main(int argc, char *argv[]) nsecs = atoi(optarg); tfnd = 1; break; + case 'h': default: /* '?' */ - fprintf(stderr, "Usage: %s [-t nsecs] [-n] name\n", - argv[0]); - exit(EXIT_FAILURE); + die_usage(prog, NULL); } } printf("flags=%d; tfnd=%d; optind=%d\n", flags, tfnd, optind); if (optind >= argc) { - fprintf(stderr, "Expected argument after options\n"); - exit(EXIT_FAILURE); + die_usage(prog, "Expected argument after options"); } printf("name argument = %s\n", argv[optind]); - - /* Other code omitted */ + printf("nsecs = %d\n", nsecs); exit(EXIT_SUCCESS); }