2 * getopt() - command option parsing
4 * Gunnar Ritter, Freiburg i. Br., Germany, March 2002.
7 /* Sccsid @(#)getopt.c 1.7 (gritter) 12/16/07 */
10 #include <sys/types.h>
14 #else /* !HAVE_ALLOCA_H */
16 #endif /* !HAVE_ALLOCA_H */
17 #endif /* HAVE_ALLOCA */
21 #define ac_alloc(n) alloca(n)
23 #else /* !HAVE_ALLOCA */
24 extern void *smalloc(size_t);
25 #define ac_alloc(n) smalloc(n)
26 #define ac_free(n) free(n)
27 #endif /* !HAVE_ALLOCA */
31 #endif /* !HAVE_SSIZE_T */
34 * One should not think that re-implementing this is necessary, but
36 * - Some libcs print weird messages.
38 * - GNU libc getopt() is totally brain-damaged, as it requires special
39 * care _not_ to reorder parameters and can't be told to work correctly
40 * with ':' as first optstring character at all.
49 error(const char *s
, int c
)
52 * Avoid including <unistd.h>, in case its getopt() declaration
55 extern ssize_t
write(int, const void *, size_t);
61 msg
= ": illegal option -- ";
64 msg
= ": option requires an argument -- ";
67 bp
= buf
= ac_alloc(strlen(s
) + strlen(msg
) + 2);
74 write(2, buf
, bp
- buf
);
79 getopt(int argc
, char *const argv
[], const char *optstring
)
82 static const char *lastp
;
85 if (optstring
[0] == ':') {
94 if (optind
>= argc
|| argv
[optind
] == 0 ||
95 argv
[optind
][0] != '-' ||
96 argv
[optind
][1] == '\0')
98 if (argv
[optind
][1] == '-' && argv
[optind
][2] == '\0') {
102 curp
= &argv
[optind
][1];
104 optopt
= curp
[0] & 0377;
105 while (optstring
[0]) {
106 if (optstring
[0] == ':') {
110 if ((optstring
[0] & 0377) == optopt
) {
111 if (optstring
[1] == ':') {
112 if (curp
[1] != '\0') {
113 optarg
= (char *)&curp
[1];
116 if ((optind
+= 2) > argc
) {
117 if (!colon
&& opterr
)
119 return colon
? ':' : '?';
121 optarg
= argv
[optind
- 1];
134 if (!colon
&& opterr
)
146 * Starting with Mac OS 10.5 Leopard, <unistd.h> turns getopt()
147 * into getopt$UNIX2003() by default. Consequently, this function
148 * is called instead of the one defined above. However, optind is
149 * still taken from this file, so in effect, options are not
150 * properly handled. Defining an own getopt$UNIX2003() function
151 * works around this issue.
154 getopt$
UNIX2003(int argc
, char *const argv
[], const char *optstring
)
156 return getopt(argc
, argv
, optstring
);
158 #endif /* __APPLE__ */