2 * getopt() - command option parsing
4 * Gunnar Ritter, Freiburg i. Br., Germany, March 2002.
10 typedef int avoid_empty_file_compiler_warning
;
13 # include <sys/types.h>
24 # define ac_alloc(n) alloca(n)
27 extern void *smalloc(size_t);
28 # define ac_alloc(n) smalloc(n)
29 # define ac_free(n) free(n)
37 * One should not think that re-implementing this is necessary, but
39 * - Some libcs print weird messages.
41 * - GNU libc getopt() is totally brain-damaged, as it requires special
42 * care _not_ to reorder parameters and can't be told to work correctly
43 * with ':' as first optstring character at all.
52 error(const char *s
, int c
)
55 * Avoid including <unistd.h>, in case its getopt() declaration
58 extern ssize_t
write(int, const void *, size_t);
64 msg
= ": illegal option -- ";
67 msg
= ": option requires an argument -- ";
70 bp
= buf
= ac_alloc(strlen(s
) + strlen(msg
) + 2);
77 write(2, buf
, bp
- buf
);
82 getopt(int argc
, char *const argv
[], const char *optstring
)
85 static const char *lastp
;
88 if (optstring
[0] == ':') {
97 if (optind
>= argc
|| argv
[optind
] == 0 ||
98 argv
[optind
][0] != '-' ||
99 argv
[optind
][1] == '\0')
101 if (argv
[optind
][1] == '-' && argv
[optind
][2] == '\0') {
105 curp
= &argv
[optind
][1];
107 optopt
= curp
[0] & 0377;
108 while (optstring
[0]) {
109 if (optstring
[0] == ':') {
113 if ((optstring
[0] & 0377) == optopt
) {
114 if (optstring
[1] == ':') {
115 if (curp
[1] != '\0') {
116 optarg
= (char *)&curp
[1];
119 if ((optind
+= 2) > argc
) {
120 if (!colon
&& opterr
)
122 return colon
? ':' : '?';
124 optarg
= argv
[optind
- 1];
137 if (!colon
&& opterr
)
149 * Starting with Mac OS 10.5 Leopard, <unistd.h> turns getopt()
150 * into getopt$UNIX2003() by default. Consequently, this function
151 * is called instead of the one defined above. However, optind is
152 * still taken from this file, so in effect, options are not
153 * properly handled. Defining an own getopt$UNIX2003() function
154 * works around this issue.
157 getopt$
UNIX2003(int argc
, char *const argv
[], const char *optstring
)
159 return getopt(argc
, argv
, optstring
);
161 # endif /* __APPLE__ */
162 #endif /* HAVE_GETOPT */