3 * From: gwyn@brl-tgr.ARPA (Doug Gwyn <gwyn>) Newsgroups: net.sources
4 * Subject: getopt library routine Date: 30 Mar 85 04:45:33 GMT
7 * getopt -- public domain version of standard System V routine
9 * Strictly enforces the System V Command Syntax Standard; provided by D A
10 * Gwyn of BRL for generic ANSI C implementations
12 * #define STRICT to prevent acceptance of clustered options with arguments
13 * and ommision of whitespace between option and arg.
19 int opterr
= 1; /* error => print message */
20 int optind
= 1; /* next argv[] index */
21 char *optarg
= NULL
; /* option parameter if any */
24 Err(name
, mess
, c
) /* returns '?' */
25 char *name
; /* program name argv[0] */
26 char *mess
; /* specific message */
27 int c
; /* defective option letter */
31 (void) fprintf(stderr
,
37 return '?'; /* erroneous-option marker */
41 getopt(argc
, argv
, optstring
) /* returns letter, '?', EOF */
42 int argc
; /* argument count from main */
43 char *argv
[]; /* argument vector from main */
44 char *optstring
; /* allowed args, e.g. "ab:c" */
46 static int sp
= 1; /* position within argument */
47 register int osp
; /* saved `sp' for param test */
49 register int oind
; /* saved `optind' for param test */
51 register int c
; /* option letter */
52 register char *cp
; /* -> option in `optstring' */
56 if (sp
== 1) /* fresh argument */
57 if (optind
>= argc
/* no more arguments */
58 || argv
[optind
][0] != '-' /* no more options */
59 || argv
[optind
][1] == '\0' /* not option; stdin */
62 else if (strcmp(argv
[optind
], "--") == 0)
64 ++optind
; /* skip over "--" */
65 return EOF
; /* "--" marks end of options */
68 c
= argv
[optind
][sp
]; /* option letter */
69 osp
= sp
++; /* get ready for next letter */
72 oind
= optind
; /* save optind for param test */
74 if (argv
[optind
][sp
] == '\0')/* end of argument */
76 ++optind
; /* get ready for next try */
77 sp
= 1; /* beginning of next argument */
80 if (c
== ':' || c
== '?' /* optstring syntax conflict */
81 || (cp
= strchr(optstring
, c
)) == NULL
/* not found */
83 return Err(argv
[0], "illegal option", c
);
85 if (cp
[1] == ':') /* option takes parameter */
90 "option must not be clustered",
94 if (sp
!= 1) /* reset by end of argument */
96 "option must be followed by white space",
101 if (oind
== optind
) /* argument w/o whitespace */
103 optarg
= &argv
[optind
][sp
];
104 sp
= 1; /* beginning of next argument */
111 "option requires an argument",
115 else /* argument w/ whitespace */
116 optarg
= argv
[optind
];
118 ++optind
; /* skip over parameter */