1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| #include <stdio.h> #include <stdlib.h> #include <getopt.h>
int main(int argc, char *argv[]) { int opt, xnum = 0; char *pstr = NULL;
while ((opt = getopt(argc, argv, ":p:x")) != -1) { printf("opt = %3d (%c); optind = %d\n", opt, opt, optind);
switch (opt) { case 'p': pstr = optarg; break; case 'x': xnum++; break; case ':': fprintf(stderr, "Missing argument!\n" "Usage: %s [-p arg] [-x]\n", argv[0]); exit(EXIT_FAILURE); case '?': fprintf(stderr, "Unrecognized option!\n" "Usage: %s [-p arg] [-x]\n", argv[0]); exit(EXIT_FAILURE); default: fprintf(stderr, "Unexpected case in switch()"); exit(EXIT_FAILURE); } }
if (xnum != 0) printf("-x was specified (count=%d)\n", xnum); if (pstr != NULL) printf("-p was specified with the value \"%s\"\n", pstr); if (optind < argc) printf("First non-option argument is \"%s\" at argv[%d]\n", argv[optind], optind);
exit(EXIT_SUCCESS); }
|