.
[glibc/history.git] / posix / getopt.c
blobb1cecd31aa43258ec408dd7cd794aaa477827212
1 /* Getopt for GNU.
2 NOTE: getopt is now part of the C library, so if you don't know what
3 "Keep this file name-space clean" means, talk to drepper@gnu.org
4 before changing it!
5 Copyright (C) 1987,88,89,90,91,92,93,94,95,96,98,99,2000,2001,2002,2003,2004
6 Free Software Foundation, Inc.
7 This file is part of the GNU C Library.
9 The GNU C Library is free software; you can redistribute it and/or
10 modify it under the terms of the GNU Lesser General Public
11 License as published by the Free Software Foundation; either
12 version 2.1 of the License, or (at your option) any later version.
14 The GNU C Library is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 Lesser General Public License for more details.
19 You should have received a copy of the GNU Lesser General Public
20 License along with the GNU C Library; if not, write to the Free
21 Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
22 02111-1307 USA. */
24 /* This tells Alpha OSF/1 not to define a getopt prototype in <stdio.h>.
25 Ditto for AIX 3.2 and <stdlib.h>. */
26 #ifndef _NO_PROTO
27 # define _NO_PROTO
28 #endif
30 #ifdef HAVE_CONFIG_H
31 # include <config.h>
32 #endif
34 #include <stdio.h>
36 /* Comment out all this code if we are using the GNU C Library, and are not
37 actually compiling the library itself. This code is part of the GNU C
38 Library, but also included in many other GNU distributions. Compiling
39 and linking in this code is a waste when using the GNU C library
40 (especially if it is a shared library). Rather than having every GNU
41 program understand `configure --with-gnu-libc' and omit the object files,
42 it is simpler to just do this in the source for each such file. */
44 #define GETOPT_INTERFACE_VERSION 2
45 #if !defined _LIBC && defined __GLIBC__ && __GLIBC__ >= 2
46 # include <gnu-versions.h>
47 # if _GNU_GETOPT_INTERFACE_VERSION == GETOPT_INTERFACE_VERSION
48 # define ELIDE_CODE
49 # endif
50 #endif
52 #ifndef ELIDE_CODE
55 /* This needs to come after some library #include
56 to get __GNU_LIBRARY__ defined. */
57 #ifdef __GNU_LIBRARY__
58 /* Don't include stdlib.h for non-GNU C libraries because some of them
59 contain conflicting prototypes for getopt. */
60 # include <stdlib.h>
61 # include <unistd.h>
62 #endif /* GNU C library. */
64 #include <string.h>
66 #ifdef VMS
67 # include <unixlib.h>
68 #endif
70 #ifdef _LIBC
71 # include <libintl.h>
72 #else
73 # include "gettext.h"
74 # define _(msgid) gettext (msgid)
75 #endif
77 #if defined _LIBC && defined USE_IN_LIBIO
78 # include <wchar.h>
79 #endif
81 #ifndef attribute_hidden
82 # define attribute_hidden
83 #endif
85 /* This version of `getopt' appears to the caller like standard Unix `getopt'
86 but it behaves differently for the user, since it allows the user
87 to intersperse the options with the other arguments.
89 As `getopt' works, it permutes the elements of ARGV so that,
90 when it is done, all the options precede everything else. Thus
91 all application programs are extended to handle flexible argument order.
93 Setting the environment variable POSIXLY_CORRECT disables permutation.
94 Then the behavior is completely standard.
96 GNU application programs can use a third alternative mode in which
97 they can distinguish the relative order of options and other arguments. */
99 #include "getopt.h"
100 #include "getopt_int.h"
102 /* For communication from `getopt' to the caller.
103 When `getopt' finds an option that takes an argument,
104 the argument value is returned here.
105 Also, when `ordering' is RETURN_IN_ORDER,
106 each non-option ARGV-element is returned here. */
108 char *optarg;
110 /* Index in ARGV of the next element to be scanned.
111 This is used for communication to and from the caller
112 and for communication between successive calls to `getopt'.
114 On entry to `getopt', zero means this is the first call; initialize.
116 When `getopt' returns -1, this is the index of the first of the
117 non-option elements that the caller should itself scan.
119 Otherwise, `optind' communicates from one call to the next
120 how much of ARGV has been scanned so far. */
122 /* 1003.2 says this must be 1 before any call. */
123 int optind = 1;
125 /* Callers store zero here to inhibit the error message
126 for unrecognized options. */
128 int opterr = 1;
130 /* Set to an option character which was unrecognized.
131 This must be initialized on some systems to avoid linking in the
132 system's own getopt implementation. */
134 int optopt = '?';
136 /* Keep a global copy of all internal members of getopt_data. */
138 static struct _getopt_data getopt_data;
141 #ifndef __GNU_LIBRARY__
143 /* Avoid depending on library functions or files
144 whose names are inconsistent. */
146 #ifndef getenv
147 extern char *getenv ();
148 #endif
150 #endif /* not __GNU_LIBRARY__ */
152 #ifdef _LIBC
153 /* Stored original parameters.
154 XXX This is no good solution. We should rather copy the args so
155 that we can compare them later. But we must not use malloc(3). */
156 extern int __libc_argc;
157 extern char **__libc_argv;
159 /* Bash 2.0 gives us an environment variable containing flags
160 indicating ARGV elements that should not be considered arguments. */
162 # ifdef USE_NONOPTION_FLAGS
163 /* Defined in getopt_init.c */
164 extern char *__getopt_nonoption_flags;
165 # endif
167 # ifdef USE_NONOPTION_FLAGS
168 # define SWAP_FLAGS(ch1, ch2) \
169 if (d->__nonoption_flags_len > 0) \
171 char __tmp = __getopt_nonoption_flags[ch1]; \
172 __getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2]; \
173 __getopt_nonoption_flags[ch2] = __tmp; \
175 # else
176 # define SWAP_FLAGS(ch1, ch2)
177 # endif
178 #else /* !_LIBC */
179 # define SWAP_FLAGS(ch1, ch2)
180 #endif /* _LIBC */
182 /* Exchange two adjacent subsequences of ARGV.
183 One subsequence is elements [first_nonopt,last_nonopt)
184 which contains all the non-options that have been skipped so far.
185 The other is elements [last_nonopt,optind), which contains all
186 the options processed since those non-options were skipped.
188 `first_nonopt' and `last_nonopt' are relocated so that they describe
189 the new indices of the non-options in ARGV after they are moved. */
191 static void
192 exchange (char **argv, struct _getopt_data *d)
194 int bottom = d->__first_nonopt;
195 int middle = d->__last_nonopt;
196 int top = d->optind;
197 char *tem;
199 /* Exchange the shorter segment with the far end of the longer segment.
200 That puts the shorter segment into the right place.
201 It leaves the longer segment in the right place overall,
202 but it consists of two parts that need to be swapped next. */
204 #if defined _LIBC && defined USE_NONOPTION_FLAGS
205 /* First make sure the handling of the `__getopt_nonoption_flags'
206 string can work normally. Our top argument must be in the range
207 of the string. */
208 if (d->__nonoption_flags_len > 0 && top >= d->__nonoption_flags_max_len)
210 /* We must extend the array. The user plays games with us and
211 presents new arguments. */
212 char *new_str = malloc (top + 1);
213 if (new_str == NULL)
214 d->__nonoption_flags_len = d->__nonoption_flags_max_len = 0;
215 else
217 memset (__mempcpy (new_str, __getopt_nonoption_flags,
218 d->__nonoption_flags_max_len),
219 '\0', top + 1 - d->__nonoption_flags_max_len);
220 d->__nonoption_flags_max_len = top + 1;
221 __getopt_nonoption_flags = new_str;
224 #endif
226 while (top > middle && middle > bottom)
228 if (top - middle > middle - bottom)
230 /* Bottom segment is the short one. */
231 int len = middle - bottom;
232 register int i;
234 /* Swap it with the top part of the top segment. */
235 for (i = 0; i < len; i++)
237 tem = argv[bottom + i];
238 argv[bottom + i] = argv[top - (middle - bottom) + i];
239 argv[top - (middle - bottom) + i] = tem;
240 SWAP_FLAGS (bottom + i, top - (middle - bottom) + i);
242 /* Exclude the moved bottom segment from further swapping. */
243 top -= len;
245 else
247 /* Top segment is the short one. */
248 int len = top - middle;
249 register int i;
251 /* Swap it with the bottom part of the bottom segment. */
252 for (i = 0; i < len; i++)
254 tem = argv[bottom + i];
255 argv[bottom + i] = argv[middle + i];
256 argv[middle + i] = tem;
257 SWAP_FLAGS (bottom + i, middle + i);
259 /* Exclude the moved top segment from further swapping. */
260 bottom += len;
264 /* Update records for the slots the non-options now occupy. */
266 d->__first_nonopt += (d->optind - d->__last_nonopt);
267 d->__last_nonopt = d->optind;
270 /* Initialize the internal data when the first call is made. */
272 static const char *
273 _getopt_initialize (int argc, char *const *argv, const char *optstring,
274 struct _getopt_data *d)
276 /* Start processing options with ARGV-element 1 (since ARGV-element 0
277 is the program name); the sequence of previously skipped
278 non-option ARGV-elements is empty. */
280 d->__first_nonopt = d->__last_nonopt = d->optind;
282 d->__nextchar = NULL;
284 d->__posixly_correct = !!getenv ("POSIXLY_CORRECT");
286 /* Determine how to handle the ordering of options and nonoptions. */
288 if (optstring[0] == '-')
290 d->__ordering = RETURN_IN_ORDER;
291 ++optstring;
293 else if (optstring[0] == '+')
295 d->__ordering = REQUIRE_ORDER;
296 ++optstring;
298 else if (d->__posixly_correct)
299 d->__ordering = REQUIRE_ORDER;
300 else
301 d->__ordering = PERMUTE;
303 #if defined _LIBC && defined USE_NONOPTION_FLAGS
304 if (!d->__posixly_correct
305 && argc == __libc_argc && argv == __libc_argv)
307 if (d->__nonoption_flags_max_len == 0)
309 if (__getopt_nonoption_flags == NULL
310 || __getopt_nonoption_flags[0] == '\0')
311 d->__nonoption_flags_max_len = -1;
312 else
314 const char *orig_str = __getopt_nonoption_flags;
315 int len = d->__nonoption_flags_max_len = strlen (orig_str);
316 if (d->__nonoption_flags_max_len < argc)
317 d->__nonoption_flags_max_len = argc;
318 __getopt_nonoption_flags =
319 (char *) malloc (d->__nonoption_flags_max_len);
320 if (__getopt_nonoption_flags == NULL)
321 d->__nonoption_flags_max_len = -1;
322 else
323 memset (__mempcpy (__getopt_nonoption_flags, orig_str, len),
324 '\0', d->__nonoption_flags_max_len - len);
327 d->__nonoption_flags_len = d->__nonoption_flags_max_len;
329 else
330 d->__nonoption_flags_len = 0;
331 #endif
333 return optstring;
336 /* Scan elements of ARGV (whose length is ARGC) for option characters
337 given in OPTSTRING.
339 If an element of ARGV starts with '-', and is not exactly "-" or "--",
340 then it is an option element. The characters of this element
341 (aside from the initial '-') are option characters. If `getopt'
342 is called repeatedly, it returns successively each of the option characters
343 from each of the option elements.
345 If `getopt' finds another option character, it returns that character,
346 updating `optind' and `nextchar' so that the next call to `getopt' can
347 resume the scan with the following option character or ARGV-element.
349 If there are no more option characters, `getopt' returns -1.
350 Then `optind' is the index in ARGV of the first ARGV-element
351 that is not an option. (The ARGV-elements have been permuted
352 so that those that are not options now come last.)
354 OPTSTRING is a string containing the legitimate option characters.
355 If an option character is seen that is not listed in OPTSTRING,
356 return '?' after printing an error message. If you set `opterr' to
357 zero, the error message is suppressed but we still return '?'.
359 If a char in OPTSTRING is followed by a colon, that means it wants an arg,
360 so the following text in the same ARGV-element, or the text of the following
361 ARGV-element, is returned in `optarg'. Two colons mean an option that
362 wants an optional arg; if there is text in the current ARGV-element,
363 it is returned in `optarg', otherwise `optarg' is set to zero.
365 If OPTSTRING starts with `-' or `+', it requests different methods of
366 handling the non-option ARGV-elements.
367 See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
369 Long-named options begin with `--' instead of `-'.
370 Their names may be abbreviated as long as the abbreviation is unique
371 or is an exact match for some defined option. If they have an
372 argument, it follows the option name in the same ARGV-element, separated
373 from the option name by a `=', or else the in next ARGV-element.
374 When `getopt' finds a long-named option, it returns 0 if that option's
375 `flag' field is nonzero, the value of the option's `val' field
376 if the `flag' field is zero.
378 The elements of ARGV aren't really const, because we permute them.
379 But we pretend they're const in the prototype to be compatible
380 with other systems.
382 LONGOPTS is a vector of `struct option' terminated by an
383 element containing a name which is zero.
385 LONGIND returns the index in LONGOPT of the long-named option found.
386 It is only valid when a long-named option has been found by the most
387 recent call.
389 If LONG_ONLY is nonzero, '-' as well as '--' can introduce
390 long-named options. */
393 _getopt_internal_r (int argc, char *const *argv, const char *optstring,
394 const struct option *longopts, int *longind,
395 int long_only, struct _getopt_data *d)
397 int print_errors = d->opterr;
398 if (optstring[0] == ':')
399 print_errors = 0;
401 if (argc < 1)
402 return -1;
404 d->optarg = NULL;
406 if (d->optind == 0 || !d->__initialized)
408 if (d->optind == 0)
409 d->optind = 1; /* Don't scan ARGV[0], the program name. */
410 optstring = _getopt_initialize (argc, argv, optstring, d);
411 d->__initialized = 1;
414 /* Test whether ARGV[optind] points to a non-option argument.
415 Either it does not have option syntax, or there is an environment flag
416 from the shell indicating it is not an option. The later information
417 is only used when the used in the GNU libc. */
418 #if defined _LIBC && defined USE_NONOPTION_FLAGS
419 # define NONOPTION_P (argv[d->optind][0] != '-' || argv[d->optind][1] == '\0' \
420 || (d->optind < d->__nonoption_flags_len \
421 && __getopt_nonoption_flags[d->optind] == '1'))
422 #else
423 # define NONOPTION_P (argv[d->optind][0] != '-' || argv[d->optind][1] == '\0')
424 #endif
426 if (d->__nextchar == NULL || *d->__nextchar == '\0')
428 /* Advance to the next ARGV-element. */
430 /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
431 moved back by the user (who may also have changed the arguments). */
432 if (d->__last_nonopt > d->optind)
433 d->__last_nonopt = d->optind;
434 if (d->__first_nonopt > d->optind)
435 d->__first_nonopt = d->optind;
437 if (d->__ordering == PERMUTE)
439 /* If we have just processed some options following some non-options,
440 exchange them so that the options come first. */
442 if (d->__first_nonopt != d->__last_nonopt
443 && d->__last_nonopt != d->optind)
444 exchange ((char **) argv, d);
445 else if (d->__last_nonopt != d->optind)
446 d->__first_nonopt = d->optind;
448 /* Skip any additional non-options
449 and extend the range of non-options previously skipped. */
451 while (d->optind < argc && NONOPTION_P)
452 d->optind++;
453 d->__last_nonopt = d->optind;
456 /* The special ARGV-element `--' means premature end of options.
457 Skip it like a null option,
458 then exchange with previous non-options as if it were an option,
459 then skip everything else like a non-option. */
461 if (d->optind != argc && !strcmp (argv[d->optind], "--"))
463 d->optind++;
465 if (d->__first_nonopt != d->__last_nonopt
466 && d->__last_nonopt != d->optind)
467 exchange ((char **) argv, d);
468 else if (d->__first_nonopt == d->__last_nonopt)
469 d->__first_nonopt = d->optind;
470 d->__last_nonopt = argc;
472 d->optind = argc;
475 /* If we have done all the ARGV-elements, stop the scan
476 and back over any non-options that we skipped and permuted. */
478 if (d->optind == argc)
480 /* Set the next-arg-index to point at the non-options
481 that we previously skipped, so the caller will digest them. */
482 if (d->__first_nonopt != d->__last_nonopt)
483 d->optind = d->__first_nonopt;
484 return -1;
487 /* If we have come to a non-option and did not permute it,
488 either stop the scan or describe it to the caller and pass it by. */
490 if (NONOPTION_P)
492 if (d->__ordering == REQUIRE_ORDER)
493 return -1;
494 d->optarg = argv[d->optind++];
495 return 1;
498 /* We have found another option-ARGV-element.
499 Skip the initial punctuation. */
501 d->__nextchar = (argv[d->optind] + 1
502 + (longopts != NULL && argv[d->optind][1] == '-'));
505 /* Decode the current option-ARGV-element. */
507 /* Check whether the ARGV-element is a long option.
509 If long_only and the ARGV-element has the form "-f", where f is
510 a valid short option, don't consider it an abbreviated form of
511 a long option that starts with f. Otherwise there would be no
512 way to give the -f short option.
514 On the other hand, if there's a long option "fubar" and
515 the ARGV-element is "-fu", do consider that an abbreviation of
516 the long option, just like "--fu", and not "-f" with arg "u".
518 This distinction seems to be the most useful approach. */
520 if (longopts != NULL
521 && (argv[d->optind][1] == '-'
522 || (long_only && (argv[d->optind][2]
523 || !strchr (optstring, argv[d->optind][1])))))
525 char *nameend;
526 const struct option *p;
527 const struct option *pfound = NULL;
528 int exact = 0;
529 int ambig = 0;
530 int indfound = -1;
531 int option_index;
533 for (nameend = d->__nextchar; *nameend && *nameend != '='; nameend++)
534 /* Do nothing. */ ;
536 /* Test all long options for either exact match
537 or abbreviated matches. */
538 for (p = longopts, option_index = 0; p->name; p++, option_index++)
539 if (!strncmp (p->name, d->__nextchar, nameend - d->__nextchar))
541 if ((unsigned int) (nameend - d->__nextchar)
542 == (unsigned int) strlen (p->name))
544 /* Exact match found. */
545 pfound = p;
546 indfound = option_index;
547 exact = 1;
548 break;
550 else if (pfound == NULL)
552 /* First nonexact match found. */
553 pfound = p;
554 indfound = option_index;
556 else if (long_only
557 || pfound->has_arg != p->has_arg
558 || pfound->flag != p->flag
559 || pfound->val != p->val)
560 /* Second or later nonexact match found. */
561 ambig = 1;
564 if (ambig && !exact)
566 if (print_errors)
568 #if defined _LIBC && defined USE_IN_LIBIO
569 char *buf;
571 if (__asprintf (&buf, _("%s: option `%s' is ambiguous\n"),
572 argv[0], argv[d->optind]) >= 0)
574 _IO_flockfile (stderr);
576 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
577 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
579 __fxprintf (NULL, "%s", buf);
581 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
582 _IO_funlockfile (stderr);
584 free (buf);
586 #else
587 fprintf (stderr, _("%s: option `%s' is ambiguous\n"),
588 argv[0], argv[d->optind]);
589 #endif
591 d->__nextchar += strlen (d->__nextchar);
592 d->optind++;
593 d->optopt = 0;
594 return '?';
597 if (pfound != NULL)
599 option_index = indfound;
600 d->optind++;
601 if (*nameend)
603 /* Don't test has_arg with >, because some C compilers don't
604 allow it to be used on enums. */
605 if (pfound->has_arg)
606 d->optarg = nameend + 1;
607 else
609 if (print_errors)
611 #if defined _LIBC && defined USE_IN_LIBIO
612 char *buf;
613 int n;
614 #endif
616 if (argv[d->optind - 1][1] == '-')
618 /* --option */
619 #if defined _LIBC && defined USE_IN_LIBIO
620 n = __asprintf (&buf, _("\
621 %s: option `--%s' doesn't allow an argument\n"),
622 argv[0], pfound->name);
623 #else
624 fprintf (stderr, _("\
625 %s: option `--%s' doesn't allow an argument\n"),
626 argv[0], pfound->name);
627 #endif
629 else
631 /* +option or -option */
632 #if defined _LIBC && defined USE_IN_LIBIO
633 n = __asprintf (&buf, _("\
634 %s: option `%c%s' doesn't allow an argument\n"),
635 argv[0], argv[d->optind - 1][0],
636 pfound->name);
637 #else
638 fprintf (stderr, _("\
639 %s: option `%c%s' doesn't allow an argument\n"),
640 argv[0], argv[d->optind - 1][0],
641 pfound->name);
642 #endif
645 #if defined _LIBC && defined USE_IN_LIBIO
646 if (n >= 0)
648 _IO_flockfile (stderr);
650 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
651 ((_IO_FILE *) stderr)->_flags2
652 |= _IO_FLAGS2_NOTCANCEL;
654 __fxprintf (NULL, "%s", buf);
656 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
657 _IO_funlockfile (stderr);
659 free (buf);
661 #endif
664 d->__nextchar += strlen (d->__nextchar);
666 d->optopt = pfound->val;
667 return '?';
670 else if (pfound->has_arg == 1)
672 if (d->optind < argc)
673 d->optarg = argv[d->optind++];
674 else
676 if (print_errors)
678 #if defined _LIBC && defined USE_IN_LIBIO
679 char *buf;
681 if (__asprintf (&buf, _("\
682 %s: option `%s' requires an argument\n"),
683 argv[0], argv[d->optind - 1]) >= 0)
685 _IO_flockfile (stderr);
687 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
688 ((_IO_FILE *) stderr)->_flags2
689 |= _IO_FLAGS2_NOTCANCEL;
691 __fxprintf (NULL, "%s", buf);
693 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
694 _IO_funlockfile (stderr);
696 free (buf);
698 #else
699 fprintf (stderr,
700 _("%s: option `%s' requires an argument\n"),
701 argv[0], argv[d->optind - 1]);
702 #endif
704 d->__nextchar += strlen (d->__nextchar);
705 d->optopt = pfound->val;
706 return optstring[0] == ':' ? ':' : '?';
709 d->__nextchar += strlen (d->__nextchar);
710 if (longind != NULL)
711 *longind = option_index;
712 if (pfound->flag)
714 *(pfound->flag) = pfound->val;
715 return 0;
717 return pfound->val;
720 /* Can't find it as a long option. If this is not getopt_long_only,
721 or the option starts with '--' or is not a valid short
722 option, then it's an error.
723 Otherwise interpret it as a short option. */
724 if (!long_only || argv[d->optind][1] == '-'
725 || strchr (optstring, *d->__nextchar) == NULL)
727 if (print_errors)
729 #if defined _LIBC && defined USE_IN_LIBIO
730 char *buf;
731 int n;
732 #endif
734 if (argv[d->optind][1] == '-')
736 /* --option */
737 #if defined _LIBC && defined USE_IN_LIBIO
738 n = __asprintf (&buf, _("%s: unrecognized option `--%s'\n"),
739 argv[0], d->__nextchar);
740 #else
741 fprintf (stderr, _("%s: unrecognized option `--%s'\n"),
742 argv[0], d->__nextchar);
743 #endif
745 else
747 /* +option or -option */
748 #if defined _LIBC && defined USE_IN_LIBIO
749 n = __asprintf (&buf, _("%s: unrecognized option `%c%s'\n"),
750 argv[0], argv[d->optind][0], d->__nextchar);
751 #else
752 fprintf (stderr, _("%s: unrecognized option `%c%s'\n"),
753 argv[0], argv[d->optind][0], d->__nextchar);
754 #endif
757 #if defined _LIBC && defined USE_IN_LIBIO
758 if (n >= 0)
760 _IO_flockfile (stderr);
762 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
763 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
765 __fxprintf (NULL, "%s", buf);
767 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
768 _IO_funlockfile (stderr);
770 free (buf);
772 #endif
774 d->__nextchar = (char *) "";
775 d->optind++;
776 d->optopt = 0;
777 return '?';
781 /* Look at and handle the next short option-character. */
784 char c = *d->__nextchar++;
785 char *temp = strchr (optstring, c);
787 /* Increment `optind' when we start to process its last character. */
788 if (*d->__nextchar == '\0')
789 ++d->optind;
791 if (temp == NULL || c == ':')
793 if (print_errors)
795 #if defined _LIBC && defined USE_IN_LIBIO
796 char *buf;
797 int n;
798 #endif
800 if (d->__posixly_correct)
802 /* 1003.2 specifies the format of this message. */
803 #if defined _LIBC && defined USE_IN_LIBIO
804 n = __asprintf (&buf, _("%s: illegal option -- %c\n"),
805 argv[0], c);
806 #else
807 fprintf (stderr, _("%s: illegal option -- %c\n"), argv[0], c);
808 #endif
810 else
812 #if defined _LIBC && defined USE_IN_LIBIO
813 n = __asprintf (&buf, _("%s: invalid option -- %c\n"),
814 argv[0], c);
815 #else
816 fprintf (stderr, _("%s: invalid option -- %c\n"), argv[0], c);
817 #endif
820 #if defined _LIBC && defined USE_IN_LIBIO
821 if (n >= 0)
823 _IO_flockfile (stderr);
825 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
826 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
828 __fxprintf (NULL, "%s", buf);
830 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
831 _IO_funlockfile (stderr);
833 free (buf);
835 #endif
837 d->optopt = c;
838 return '?';
840 /* Convenience. Treat POSIX -W foo same as long option --foo */
841 if (temp[0] == 'W' && temp[1] == ';')
843 char *nameend;
844 const struct option *p;
845 const struct option *pfound = NULL;
846 int exact = 0;
847 int ambig = 0;
848 int indfound = 0;
849 int option_index;
851 /* This is an option that requires an argument. */
852 if (*d->__nextchar != '\0')
854 d->optarg = d->__nextchar;
855 /* If we end this ARGV-element by taking the rest as an arg,
856 we must advance to the next element now. */
857 d->optind++;
859 else if (d->optind == argc)
861 if (print_errors)
863 /* 1003.2 specifies the format of this message. */
864 #if defined _LIBC && defined USE_IN_LIBIO
865 char *buf;
867 if (__asprintf (&buf,
868 _("%s: option requires an argument -- %c\n"),
869 argv[0], c) >= 0)
871 _IO_flockfile (stderr);
873 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
874 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
876 __fxprintf (NULL, "%s", buf);
878 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
879 _IO_funlockfile (stderr);
881 free (buf);
883 #else
884 fprintf (stderr, _("%s: option requires an argument -- %c\n"),
885 argv[0], c);
886 #endif
888 d->optopt = c;
889 if (optstring[0] == ':')
890 c = ':';
891 else
892 c = '?';
893 return c;
895 else
896 /* We already incremented `d->optind' once;
897 increment it again when taking next ARGV-elt as argument. */
898 d->optarg = argv[d->optind++];
900 /* optarg is now the argument, see if it's in the
901 table of longopts. */
903 for (d->__nextchar = nameend = d->optarg; *nameend && *nameend != '=';
904 nameend++)
905 /* Do nothing. */ ;
907 /* Test all long options for either exact match
908 or abbreviated matches. */
909 for (p = longopts, option_index = 0; p->name; p++, option_index++)
910 if (!strncmp (p->name, d->__nextchar, nameend - d->__nextchar))
912 if ((unsigned int) (nameend - d->__nextchar) == strlen (p->name))
914 /* Exact match found. */
915 pfound = p;
916 indfound = option_index;
917 exact = 1;
918 break;
920 else if (pfound == NULL)
922 /* First nonexact match found. */
923 pfound = p;
924 indfound = option_index;
926 else
927 /* Second or later nonexact match found. */
928 ambig = 1;
930 if (ambig && !exact)
932 if (print_errors)
934 #if defined _LIBC && defined USE_IN_LIBIO
935 char *buf;
937 if (__asprintf (&buf, _("%s: option `-W %s' is ambiguous\n"),
938 argv[0], argv[d->optind]) >= 0)
940 _IO_flockfile (stderr);
942 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
943 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
945 __fxprintf (NULL, "%s", buf);
947 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
948 _IO_funlockfile (stderr);
950 free (buf);
952 #else
953 fprintf (stderr, _("%s: option `-W %s' is ambiguous\n"),
954 argv[0], argv[d->optind]);
955 #endif
957 d->__nextchar += strlen (d->__nextchar);
958 d->optind++;
959 return '?';
961 if (pfound != NULL)
963 option_index = indfound;
964 if (*nameend)
966 /* Don't test has_arg with >, because some C compilers don't
967 allow it to be used on enums. */
968 if (pfound->has_arg)
969 d->optarg = nameend + 1;
970 else
972 if (print_errors)
974 #if defined _LIBC && defined USE_IN_LIBIO
975 char *buf;
977 if (__asprintf (&buf, _("\
978 %s: option `-W %s' doesn't allow an argument\n"),
979 argv[0], pfound->name) >= 0)
981 _IO_flockfile (stderr);
983 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
984 ((_IO_FILE *) stderr)->_flags2
985 |= _IO_FLAGS2_NOTCANCEL;
987 __fxprintf (NULL, "%s", buf);
989 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
990 _IO_funlockfile (stderr);
992 free (buf);
994 #else
995 fprintf (stderr, _("\
996 %s: option `-W %s' doesn't allow an argument\n"),
997 argv[0], pfound->name);
998 #endif
1001 d->__nextchar += strlen (d->__nextchar);
1002 return '?';
1005 else if (pfound->has_arg == 1)
1007 if (d->optind < argc)
1008 d->optarg = argv[d->optind++];
1009 else
1011 if (print_errors)
1013 #if defined _LIBC && defined USE_IN_LIBIO
1014 char *buf;
1016 if (__asprintf (&buf, _("\
1017 %s: option `%s' requires an argument\n"),
1018 argv[0], argv[d->optind - 1]) >= 0)
1020 _IO_flockfile (stderr);
1022 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
1023 ((_IO_FILE *) stderr)->_flags2
1024 |= _IO_FLAGS2_NOTCANCEL;
1026 __fxprintf (NULL, "%s", buf);
1028 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
1029 _IO_funlockfile (stderr);
1031 free (buf);
1033 #else
1034 fprintf (stderr,
1035 _("%s: option `%s' requires an argument\n"),
1036 argv[0], argv[d->optind - 1]);
1037 #endif
1039 d->__nextchar += strlen (d->__nextchar);
1040 return optstring[0] == ':' ? ':' : '?';
1043 d->__nextchar += strlen (d->__nextchar);
1044 if (longind != NULL)
1045 *longind = option_index;
1046 if (pfound->flag)
1048 *(pfound->flag) = pfound->val;
1049 return 0;
1051 return pfound->val;
1053 d->__nextchar = NULL;
1054 return 'W'; /* Let the application handle it. */
1056 if (temp[1] == ':')
1058 if (temp[2] == ':')
1060 /* This is an option that accepts an argument optionally. */
1061 if (*d->__nextchar != '\0')
1063 d->optarg = d->__nextchar;
1064 d->optind++;
1066 else
1067 d->optarg = NULL;
1068 d->__nextchar = NULL;
1070 else
1072 /* This is an option that requires an argument. */
1073 if (*d->__nextchar != '\0')
1075 d->optarg = d->__nextchar;
1076 /* If we end this ARGV-element by taking the rest as an arg,
1077 we must advance to the next element now. */
1078 d->optind++;
1080 else if (d->optind == argc)
1082 if (print_errors)
1084 /* 1003.2 specifies the format of this message. */
1085 #if defined _LIBC && defined USE_IN_LIBIO
1086 char *buf;
1088 if (__asprintf (&buf, _("\
1089 %s: option requires an argument -- %c\n"),
1090 argv[0], c) >= 0)
1092 _IO_flockfile (stderr);
1094 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
1095 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
1097 __fxprintf (NULL, "%s", buf);
1099 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
1100 _IO_funlockfile (stderr);
1102 free (buf);
1104 #else
1105 fprintf (stderr,
1106 _("%s: option requires an argument -- %c\n"),
1107 argv[0], c);
1108 #endif
1110 d->optopt = c;
1111 if (optstring[0] == ':')
1112 c = ':';
1113 else
1114 c = '?';
1116 else
1117 /* We already incremented `optind' once;
1118 increment it again when taking next ARGV-elt as argument. */
1119 d->optarg = argv[d->optind++];
1120 d->__nextchar = NULL;
1123 return c;
1128 _getopt_internal (int argc, char *const *argv, const char *optstring,
1129 const struct option *longopts, int *longind, int long_only)
1131 int result;
1133 getopt_data.optind = optind;
1134 getopt_data.opterr = opterr;
1136 result = _getopt_internal_r (argc, argv, optstring, longopts,
1137 longind, long_only, &getopt_data);
1139 optind = getopt_data.optind;
1140 optarg = getopt_data.optarg;
1141 optopt = getopt_data.optopt;
1143 return result;
1147 getopt (int argc, char *const *argv, const char *optstring)
1149 return _getopt_internal (argc, argv, optstring,
1150 (const struct option *) 0,
1151 (int *) 0,
1155 #endif /* Not ELIDE_CODE. */
1157 #ifdef TEST
1159 /* Compile with -DTEST to make an executable for use in testing
1160 the above definition of `getopt'. */
1163 main (int argc, char **argv)
1165 int c;
1166 int digit_optind = 0;
1168 while (1)
1170 int this_option_optind = optind ? optind : 1;
1172 c = getopt (argc, argv, "abc:d:0123456789");
1173 if (c == -1)
1174 break;
1176 switch (c)
1178 case '0':
1179 case '1':
1180 case '2':
1181 case '3':
1182 case '4':
1183 case '5':
1184 case '6':
1185 case '7':
1186 case '8':
1187 case '9':
1188 if (digit_optind != 0 && digit_optind != this_option_optind)
1189 printf ("digits occur in two different argv-elements.\n");
1190 digit_optind = this_option_optind;
1191 printf ("option %c\n", c);
1192 break;
1194 case 'a':
1195 printf ("option a\n");
1196 break;
1198 case 'b':
1199 printf ("option b\n");
1200 break;
1202 case 'c':
1203 printf ("option c with value `%s'\n", optarg);
1204 break;
1206 case '?':
1207 break;
1209 default:
1210 printf ("?? getopt returned character code 0%o ??\n", c);
1214 if (optind < argc)
1216 printf ("non-option ARGV-elements: ");
1217 while (optind < argc)
1218 printf ("%s ", argv[optind++]);
1219 printf ("\n");
1222 exit (0);
1225 #endif /* TEST */