4 * Simple POSIX getopt(), no GNU extensions...
12 int optind
, opterr
, optopt
;
13 static struct getopt_private_state
{
15 const char *last_optstring
;
16 char *const *last_argv
;
19 int getopt(int argc
, char *const *argv
, const char *optstring
)
25 /* getopt() relies on a number of different global state
26 variables, which can make this really confusing if there is
27 more than one use of getopt() in the same program. This
28 attempts to detect that situation by detecting if the
29 "optstring" or "argv" argument have changed since last time
30 we were called; if so, reinitialize the query state. */
32 if (optstring
!= pvt
.last_optstring
|| argv
!= pvt
.last_argv
||
33 optind
< 1 || optind
> argc
) {
34 /* optind doesn't match the current query */
35 pvt
.last_optstring
= optstring
;
43 /* First, eliminate all non-option cases */
45 if (!carg
|| carg
[0] != '-' || !carg
[1]) {
49 if (carg
[1] == '-' && !carg
[2]) {
54 if ((uintptr_t) (pvt
.optptr
- carg
) > (uintptr_t) strlen(carg
)) {
55 /* Someone frobbed optind, change to new opt. */
56 pvt
.optptr
= carg
+ 1;
61 if (opt
!= ':' && (osptr
= strchr(optstring
, opt
))) {
62 if (osptr
[1] == ':') {
64 /* Argument-taking option with attached
66 optarg
= (char *)pvt
.optptr
;
69 /* Argument-taking option with non-attached
71 if (argv
[optind
+ 1]) {
72 optarg
= (char *)argv
[optind
+1];
75 /* Missing argument */
77 return (optstring
[0] == ':')
83 /* Non-argument-taking option */
84 /* pvt.optptr will remember the exact position to