2 #include <string.h> /* strchr */
18 int getopt(int argc
, char **argv
, char *str
)
20 static int a
=0; /* index into argv[optind] */
21 char *s
; /* index into str */
22 static int opt
=0; /* are we currently looking at an option? */
23 static int state
=NIL
; /* current state */
28 if (optind
>= argc
) return FINISHED
;
30 /* end of current arg? */
31 if (argv
[optind
][a
]==0)
33 optind
++; /* move on to next arg */
34 if (optind
>= argc
) return FINISHED
; /* nothing more to do */
39 optarg
= argv
[optind
]; /* give it a default value */
41 /* look for next option */
42 /* starting a new argument? */
46 if (argv
[optind
][a
]=='-' || argv
[optind
][a
]=='/')
50 /* if optarg is a single "-", finished */
51 if (argv
[optind
][a
]==0)
56 state
= OPT
; /* now processing an opt */
58 /* not switched, must be an arg */
61 else /* not a new argument */
63 if (state
!= OPT
) { printf("state!=OPT\n"); return '?'; }
67 s
= strchr(str
, argv
[optind
][a
]);
70 fprintf(stderr
,"unknown option '%c'\n", argv
[optind
][a
]);
78 if (argv
[optind
][a
]==':') /* allow -o:str */
81 if (argv
[optind
][a
]==0) /* handle -o str */
84 if (optind
>= argc
) /* oops, no optarg */
86 fprintf(stderr
,"option '%c' requires an argument\n", *s
);
93 optarg
= argv
[optind
]+a
; /* no longer in arg */
94 optind
++; /* advance to next arg */
96 state
= NIL
; /* reset state */
99 else return *s
; /* got valid option */