box-o-sand/oldstuff/gnu-c/getopt-example.c
2015-06-22 13:15:42 -05:00

55 lines
1.1 KiB
C

/*
* Example getopt usage mostly from getopt(3)
*/
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <libgen.h>
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;
prog = basename(argv[0]);
while ((opt = getopt(argc, argv, "hnt:")) != -1) {
switch (opt) {
case 'n':
flags = 1;
break;
case 't':
nsecs = atoi(optarg);
tfnd = 1;
break;
case 'h':
default: /* '?' */
die_usage(prog, NULL);
}
}
printf("flags=%d; tfnd=%d; optind=%d\n", flags, tfnd, optind);
if (optind >= argc) {
die_usage(prog, "Expected argument after options");
}
printf("name argument = %s\n", argv[optind]);
printf("nsecs = %d\n", nsecs);
exit(EXIT_SUCCESS);
}