.
[coreutils.git] / lib / getopt.c
blob6dcdbebf5e8cb433630a4a79ce83e188ad89a34b
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!
6 Copyright (C) 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995,
7 1996, 1998, 1999, 2000, 2001, 2002, 2003 Free Software Foundation,
8 Inc.
10 This file is part of the GNU C Library.
12 This program is free software; you can redistribute it and/or modify
13 it under the terms of the GNU General Public License as published by
14 the Free Software Foundation; either version 2, or (at your option)
15 any later version.
17 This program is distributed in the hope that it will be useful,
18 but WITHOUT ANY WARRANTY; without even the implied warranty of
19 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 GNU General Public License for more details.
22 You should have received a copy of the GNU General Public License along
23 with this program; if not, write to the Free Software Foundation,
24 Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
26 /* This tells Alpha OSF/1 not to define a getopt prototype in <stdio.h>.
27 Ditto for AIX 3.2 and <stdlib.h>. */
28 #ifndef _NO_PROTO
29 # define _NO_PROTO
30 #endif
32 #ifdef HAVE_CONFIG_H
33 # include <config.h>
34 #endif
36 #include <stdio.h>
38 /* Comment out all this code if we are using the GNU C Library, and are not
39 actually compiling the library itself. This code is part of the GNU C
40 Library, but also included in many other GNU distributions. Compiling
41 and linking in this code is a waste when using the GNU C library
42 (especially if it is a shared library). Rather than having every GNU
43 program understand `configure --with-gnu-libc' and omit the object files,
44 it is simpler to just do this in the source for each such file. */
46 #define GETOPT_INTERFACE_VERSION 2
47 #if !defined _LIBC && defined __GLIBC__ && __GLIBC__ >= 2
48 # include <gnu-versions.h>
49 # if _GNU_GETOPT_INTERFACE_VERSION == GETOPT_INTERFACE_VERSION
50 # define ELIDE_CODE
51 # endif
52 #endif
54 #ifndef ELIDE_CODE
57 /* This needs to come after some library #include
58 to get __GNU_LIBRARY__ defined. */
59 #ifdef __GNU_LIBRARY__
60 /* Don't include stdlib.h for non-GNU C libraries because some of them
61 contain conflicting prototypes for getopt. */
62 # include <stdlib.h>
63 # include <unistd.h>
64 #endif /* GNU C library. */
66 #include <string.h>
68 #ifdef VMS
69 # include <unixlib.h>
70 #endif
72 #ifdef _LIBC
73 # include <libintl.h>
74 #else
75 /* This is for other GNU distributions with internationalized messages. */
76 # include "gettext.h"
77 #endif
78 #define _(msgid) gettext (msgid)
80 #if defined _LIBC && defined USE_IN_LIBIO
81 # include <wchar.h>
82 #endif
84 #ifndef attribute_hidden
85 # define attribute_hidden
86 #endif
88 /* This version of `getopt' appears to the caller like standard Unix `getopt'
89 but it behaves differently for the user, since it allows the user
90 to intersperse the options with the other arguments.
92 As `getopt' works, it permutes the elements of ARGV so that,
93 when it is done, all the options precede everything else. Thus
94 all application programs are extended to handle flexible argument order.
96 Setting the environment variable POSIXLY_CORRECT disables permutation.
97 Then the behavior is completely standard.
99 GNU application programs can use a third alternative mode in which
100 they can distinguish the relative order of options and other arguments. */
102 #include "getopt.h"
104 /* For communication from `getopt' to the caller.
105 When `getopt' finds an option that takes an argument,
106 the argument value is returned here.
107 Also, when `ordering' is RETURN_IN_ORDER,
108 each non-option ARGV-element is returned here. */
110 char *optarg;
112 /* Index in ARGV of the next element to be scanned.
113 This is used for communication to and from the caller
114 and for communication between successive calls to `getopt'.
116 On entry to `getopt', zero means this is the first call; initialize.
118 When `getopt' returns -1, this is the index of the first of the
119 non-option elements that the caller should itself scan.
121 Otherwise, `optind' communicates from one call to the next
122 how much of ARGV has been scanned so far. */
124 /* 1003.2 says this must be 1 before any call. */
125 int optind = 1;
127 /* Formerly, initialization of getopt depended on optind==0, which
128 causes problems with re-calling getopt as programs generally don't
129 know that. */
131 int __getopt_initialized attribute_hidden;
133 /* The next char to be scanned in the option-element
134 in which the last option character we returned was found.
135 This allows us to pick up the scan where we left off.
137 If this is zero, or a null string, it means resume the scan
138 by advancing to the next ARGV-element. */
140 static char *nextchar;
142 /* Callers store zero here to inhibit the error message
143 for unrecognized options. */
145 int opterr = 1;
147 /* Set to an option character which was unrecognized.
148 This must be initialized on some systems to avoid linking in the
149 system's own getopt implementation. */
151 int optopt = '?';
153 /* Describe how to deal with options that follow non-option ARGV-elements.
155 If the caller did not specify anything,
156 the default is REQUIRE_ORDER if the environment variable
157 POSIXLY_CORRECT is defined, PERMUTE otherwise.
159 REQUIRE_ORDER means don't recognize them as options;
160 stop option processing when the first non-option is seen.
161 This is what Unix does.
162 This mode of operation is selected by either setting the environment
163 variable POSIXLY_CORRECT, or using `+' as the first character
164 of the list of option characters.
166 PERMUTE is the default. We permute the contents of ARGV as we scan,
167 so that eventually all the non-options are at the end. This allows options
168 to be given in any order, even with programs that were not written to
169 expect this.
171 RETURN_IN_ORDER is an option available to programs that were written
172 to expect options and other ARGV-elements in any order and that care about
173 the ordering of the two. We describe each non-option ARGV-element
174 as if it were the argument of an option with character code 1.
175 Using `-' as the first character of the list of option characters
176 selects this mode of operation.
178 The special argument `--' forces an end of option-scanning regardless
179 of the value of `ordering'. In the case of RETURN_IN_ORDER, only
180 `--' can cause `getopt' to return -1 with `optind' != ARGC. */
182 static enum
184 REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER
185 } ordering;
187 /* Value of POSIXLY_CORRECT environment variable. */
188 static char *posixly_correct;
190 #ifndef __GNU_LIBRARY__
192 /* Avoid depending on library functions or files
193 whose names are inconsistent. */
195 #ifndef getenv
196 extern char *getenv ();
197 #endif
199 #endif /* not __GNU_LIBRARY__ */
201 /* Handle permutation of arguments. */
203 /* Describe the part of ARGV that contains non-options that have
204 been skipped. `first_nonopt' is the index in ARGV of the first of them;
205 `last_nonopt' is the index after the last of them. */
207 static int first_nonopt;
208 static int last_nonopt;
210 #ifdef _LIBC
211 /* Stored original parameters.
212 XXX This is no good solution. We should rather copy the args so
213 that we can compare them later. But we must not use malloc(3). */
214 extern int __libc_argc;
215 extern char **__libc_argv;
217 /* Bash 2.0 gives us an environment variable containing flags
218 indicating ARGV elements that should not be considered arguments. */
220 # ifdef USE_NONOPTION_FLAGS
221 /* Defined in getopt_init.c */
222 extern char *__getopt_nonoption_flags;
224 static int nonoption_flags_max_len;
225 static int nonoption_flags_len;
226 # endif
228 # ifdef USE_NONOPTION_FLAGS
229 # define SWAP_FLAGS(ch1, ch2) \
230 if (nonoption_flags_len > 0) \
232 char __tmp = __getopt_nonoption_flags[ch1]; \
233 __getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2]; \
234 __getopt_nonoption_flags[ch2] = __tmp; \
236 # else
237 # define SWAP_FLAGS(ch1, ch2)
238 # endif
239 #else /* !_LIBC */
240 # define SWAP_FLAGS(ch1, ch2)
241 #endif /* _LIBC */
243 /* Exchange two adjacent subsequences of ARGV.
244 One subsequence is elements [first_nonopt,last_nonopt)
245 which contains all the non-options that have been skipped so far.
246 The other is elements [last_nonopt,optind), which contains all
247 the options processed since those non-options were skipped.
249 `first_nonopt' and `last_nonopt' are relocated so that they describe
250 the new indices of the non-options in ARGV after they are moved. */
252 static void
253 exchange (char **argv)
255 int bottom = first_nonopt;
256 int middle = last_nonopt;
257 int top = optind;
258 char *tem;
260 /* Exchange the shorter segment with the far end of the longer segment.
261 That puts the shorter segment into the right place.
262 It leaves the longer segment in the right place overall,
263 but it consists of two parts that need to be swapped next. */
265 #if defined _LIBC && defined USE_NONOPTION_FLAGS
266 /* First make sure the handling of the `__getopt_nonoption_flags'
267 string can work normally. Our top argument must be in the range
268 of the string. */
269 if (nonoption_flags_len > 0 && top >= nonoption_flags_max_len)
271 /* We must extend the array. The user plays games with us and
272 presents new arguments. */
273 char *new_str = malloc (top + 1);
274 if (new_str == NULL)
275 nonoption_flags_len = nonoption_flags_max_len = 0;
276 else
278 memset (__mempcpy (new_str, __getopt_nonoption_flags,
279 nonoption_flags_max_len),
280 '\0', top + 1 - nonoption_flags_max_len);
281 nonoption_flags_max_len = top + 1;
282 __getopt_nonoption_flags = new_str;
285 #endif
287 while (top > middle && middle > bottom)
289 if (top - middle > middle - bottom)
291 /* Bottom segment is the short one. */
292 int len = middle - bottom;
293 register int i;
295 /* Swap it with the top part of the top segment. */
296 for (i = 0; i < len; i++)
298 tem = argv[bottom + i];
299 argv[bottom + i] = argv[top - (middle - bottom) + i];
300 argv[top - (middle - bottom) + i] = tem;
301 SWAP_FLAGS (bottom + i, top - (middle - bottom) + i);
303 /* Exclude the moved bottom segment from further swapping. */
304 top -= len;
306 else
308 /* Top segment is the short one. */
309 int len = top - middle;
310 register int i;
312 /* Swap it with the bottom part of the bottom segment. */
313 for (i = 0; i < len; i++)
315 tem = argv[bottom + i];
316 argv[bottom + i] = argv[middle + i];
317 argv[middle + i] = tem;
318 SWAP_FLAGS (bottom + i, middle + i);
320 /* Exclude the moved top segment from further swapping. */
321 bottom += len;
325 /* Update records for the slots the non-options now occupy. */
327 first_nonopt += (optind - last_nonopt);
328 last_nonopt = optind;
331 /* Initialize the internal data when the first call is made. */
333 static const char *
334 _getopt_initialize (int argc, char *const *argv, const char *optstring)
336 /* Start processing options with ARGV-element 1 (since ARGV-element 0
337 is the program name); the sequence of previously skipped
338 non-option ARGV-elements is empty. */
340 first_nonopt = last_nonopt = optind;
342 nextchar = NULL;
344 posixly_correct = getenv ("POSIXLY_CORRECT");
346 /* Determine how to handle the ordering of options and nonoptions. */
348 if (optstring[0] == '-')
350 ordering = RETURN_IN_ORDER;
351 ++optstring;
353 else if (optstring[0] == '+')
355 ordering = REQUIRE_ORDER;
356 ++optstring;
358 else if (posixly_correct != NULL)
359 ordering = REQUIRE_ORDER;
360 else
361 ordering = PERMUTE;
363 #if defined _LIBC && defined USE_NONOPTION_FLAGS
364 if (posixly_correct == NULL
365 && argc == __libc_argc && argv == __libc_argv)
367 if (nonoption_flags_max_len == 0)
369 if (__getopt_nonoption_flags == NULL
370 || __getopt_nonoption_flags[0] == '\0')
371 nonoption_flags_max_len = -1;
372 else
374 const char *orig_str = __getopt_nonoption_flags;
375 int len = nonoption_flags_max_len = strlen (orig_str);
376 if (nonoption_flags_max_len < argc)
377 nonoption_flags_max_len = argc;
378 __getopt_nonoption_flags =
379 (char *) malloc (nonoption_flags_max_len);
380 if (__getopt_nonoption_flags == NULL)
381 nonoption_flags_max_len = -1;
382 else
383 memset (__mempcpy (__getopt_nonoption_flags, orig_str, len),
384 '\0', nonoption_flags_max_len - len);
387 nonoption_flags_len = nonoption_flags_max_len;
389 else
390 nonoption_flags_len = 0;
391 #endif
393 return optstring;
396 /* Scan elements of ARGV (whose length is ARGC) for option characters
397 given in OPTSTRING.
399 If an element of ARGV starts with '-', and is not exactly "-" or "--",
400 then it is an option element. The characters of this element
401 (aside from the initial '-') are option characters. If `getopt'
402 is called repeatedly, it returns successively each of the option characters
403 from each of the option elements.
405 If `getopt' finds another option character, it returns that character,
406 updating `optind' and `nextchar' so that the next call to `getopt' can
407 resume the scan with the following option character or ARGV-element.
409 If there are no more option characters, `getopt' returns -1.
410 Then `optind' is the index in ARGV of the first ARGV-element
411 that is not an option. (The ARGV-elements have been permuted
412 so that those that are not options now come last.)
414 OPTSTRING is a string containing the legitimate option characters.
415 If an option character is seen that is not listed in OPTSTRING,
416 return '?' after printing an error message. If you set `opterr' to
417 zero, the error message is suppressed but we still return '?'.
419 If a char in OPTSTRING is followed by a colon, that means it wants an arg,
420 so the following text in the same ARGV-element, or the text of the following
421 ARGV-element, is returned in `optarg'. Two colons mean an option that
422 wants an optional arg; if there is text in the current ARGV-element,
423 it is returned in `optarg', otherwise `optarg' is set to zero.
425 If OPTSTRING starts with `-' or `+', it requests different methods of
426 handling the non-option ARGV-elements.
427 See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
429 Long-named options begin with `--' instead of `-'.
430 Their names may be abbreviated as long as the abbreviation is unique
431 or is an exact match for some defined option. If they have an
432 argument, it follows the option name in the same ARGV-element, separated
433 from the option name by a `=', or else the in next ARGV-element.
434 When `getopt' finds a long-named option, it returns 0 if that option's
435 `flag' field is nonzero, the value of the option's `val' field
436 if the `flag' field is zero.
438 The elements of ARGV aren't really const, because we permute them.
439 But we pretend they're const in the prototype to be compatible
440 with other systems.
442 LONGOPTS is a vector of `struct option' terminated by an
443 element containing a name which is zero.
445 LONGIND returns the index in LONGOPT of the long-named option found.
446 It is only valid when a long-named option has been found by the most
447 recent call.
449 If LONG_ONLY is nonzero, '-' as well as '--' can introduce
450 long-named options. */
453 _getopt_internal (int argc, char *const *argv,
454 const char *optstring, const struct option *longopts,
455 int *longind, int long_only)
457 int print_errors = opterr;
458 if (optstring[0] == ':')
459 print_errors = 0;
461 if (argc < 1)
462 return -1;
464 optarg = NULL;
466 if (optind == 0 || !__getopt_initialized)
468 if (optind == 0)
469 optind = 1; /* Don't scan ARGV[0], the program name. */
470 optstring = _getopt_initialize (argc, argv, optstring);
471 __getopt_initialized = 1;
474 /* Test whether ARGV[optind] points to a non-option argument.
475 Either it does not have option syntax, or there is an environment flag
476 from the shell indicating it is not an option. The later information
477 is only used when the used in the GNU libc. */
478 #if defined _LIBC && defined USE_NONOPTION_FLAGS
479 # define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0' \
480 || (optind < nonoption_flags_len \
481 && __getopt_nonoption_flags[optind] == '1'))
482 #else
483 # define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0')
484 #endif
486 if (nextchar == NULL || *nextchar == '\0')
488 /* Advance to the next ARGV-element. */
490 /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
491 moved back by the user (who may also have changed the arguments). */
492 if (last_nonopt > optind)
493 last_nonopt = optind;
494 if (first_nonopt > optind)
495 first_nonopt = optind;
497 if (ordering == PERMUTE)
499 /* If we have just processed some options following some non-options,
500 exchange them so that the options come first. */
502 if (first_nonopt != last_nonopt && last_nonopt != optind)
503 exchange ((char **) argv);
504 else if (last_nonopt != optind)
505 first_nonopt = optind;
507 /* Skip any additional non-options
508 and extend the range of non-options previously skipped. */
510 while (optind < argc && NONOPTION_P)
511 optind++;
512 last_nonopt = optind;
515 /* The special ARGV-element `--' means premature end of options.
516 Skip it like a null option,
517 then exchange with previous non-options as if it were an option,
518 then skip everything else like a non-option. */
520 if (optind != argc && !strcmp (argv[optind], "--"))
522 optind++;
524 if (first_nonopt != last_nonopt && last_nonopt != optind)
525 exchange ((char **) argv);
526 else if (first_nonopt == last_nonopt)
527 first_nonopt = optind;
528 last_nonopt = argc;
530 optind = argc;
533 /* If we have done all the ARGV-elements, stop the scan
534 and back over any non-options that we skipped and permuted. */
536 if (optind == argc)
538 /* Set the next-arg-index to point at the non-options
539 that we previously skipped, so the caller will digest them. */
540 if (first_nonopt != last_nonopt)
541 optind = first_nonopt;
542 return -1;
545 /* If we have come to a non-option and did not permute it,
546 either stop the scan or describe it to the caller and pass it by. */
548 if (NONOPTION_P)
550 if (ordering == REQUIRE_ORDER)
551 return -1;
552 optarg = argv[optind++];
553 return 1;
556 /* We have found another option-ARGV-element.
557 Skip the initial punctuation. */
559 nextchar = (argv[optind] + 1
560 + (longopts != NULL && argv[optind][1] == '-'));
563 /* Decode the current option-ARGV-element. */
565 /* Check whether the ARGV-element is a long option.
567 If long_only and the ARGV-element has the form "-f", where f is
568 a valid short option, don't consider it an abbreviated form of
569 a long option that starts with f. Otherwise there would be no
570 way to give the -f short option.
572 On the other hand, if there's a long option "fubar" and
573 the ARGV-element is "-fu", do consider that an abbreviation of
574 the long option, just like "--fu", and not "-f" with arg "u".
576 This distinction seems to be the most useful approach. */
578 if (longopts != NULL
579 && (argv[optind][1] == '-'
580 || (long_only
581 && (argv[optind][2] || !strchr (optstring, argv[optind][1])))))
583 char *nameend;
584 const struct option *p;
585 const struct option *pfound = NULL;
586 int exact = 0;
587 int ambig = 0;
588 int indfound = -1;
589 int option_index;
591 for (nameend = nextchar; *nameend && *nameend != '='; nameend++)
592 /* Do nothing. */ ;
594 /* Test all long options for either exact match
595 or abbreviated matches. */
596 for (p = longopts, option_index = 0; p->name; p++, option_index++)
597 if (!strncmp (p->name, nextchar, nameend - nextchar))
599 if ((unsigned int) (nameend - nextchar)
600 == (unsigned int) strlen (p->name))
602 /* Exact match found. */
603 pfound = p;
604 indfound = option_index;
605 exact = 1;
606 break;
608 else if (pfound == NULL)
610 /* First nonexact match found. */
611 pfound = p;
612 indfound = option_index;
614 else if (long_only
615 || pfound->has_arg != p->has_arg
616 || pfound->flag != p->flag
617 || pfound->val != p->val)
618 /* Second or later nonexact match found. */
619 ambig = 1;
622 if (ambig && !exact)
624 if (print_errors)
626 #if defined _LIBC && defined USE_IN_LIBIO
627 char *buf;
629 if (__asprintf (&buf, _("%s: option `%s' is ambiguous\n"),
630 argv[0], argv[optind]) >= 0)
633 if (_IO_fwide (stderr, 0) > 0)
634 __fwprintf (stderr, L"%s", buf);
635 else
636 fputs (buf, stderr);
638 free (buf);
640 #else
641 fprintf (stderr, _("%s: option `%s' is ambiguous\n"),
642 argv[0], argv[optind]);
643 #endif
645 nextchar += strlen (nextchar);
646 optind++;
647 optopt = 0;
648 return '?';
651 if (pfound != NULL)
653 option_index = indfound;
654 optind++;
655 if (*nameend)
657 /* Don't test has_arg with >, because some C compilers don't
658 allow it to be used on enums. */
659 if (pfound->has_arg)
660 optarg = nameend + 1;
661 else
663 if (print_errors)
665 #if defined _LIBC && defined USE_IN_LIBIO
666 char *buf;
667 int n;
668 #endif
670 if (argv[optind - 1][1] == '-')
672 /* --option */
673 #if defined _LIBC && defined USE_IN_LIBIO
674 n = __asprintf (&buf, _("\
675 %s: option `--%s' doesn't allow an argument\n"),
676 argv[0], pfound->name);
677 #else
678 fprintf (stderr, _("\
679 %s: option `--%s' doesn't allow an argument\n"),
680 argv[0], pfound->name);
681 #endif
683 else
685 /* +option or -option */
686 #if defined _LIBC && defined USE_IN_LIBIO
687 n = __asprintf (&buf, _("\
688 %s: option `%c%s' doesn't allow an argument\n"),
689 argv[0], argv[optind - 1][0],
690 pfound->name);
691 #else
692 fprintf (stderr, _("\
693 %s: option `%c%s' doesn't allow an argument\n"),
694 argv[0], argv[optind - 1][0], pfound->name);
695 #endif
698 #if defined _LIBC && defined USE_IN_LIBIO
699 if (n >= 0)
701 if (_IO_fwide (stderr, 0) > 0)
702 __fwprintf (stderr, L"%s", buf);
703 else
704 fputs (buf, stderr);
706 free (buf);
708 #endif
711 nextchar += strlen (nextchar);
713 optopt = pfound->val;
714 return '?';
717 else if (pfound->has_arg == 1)
719 if (optind < argc)
720 optarg = argv[optind++];
721 else
723 if (print_errors)
725 #if defined _LIBC && defined USE_IN_LIBIO
726 char *buf;
728 if (__asprintf (&buf, _("\
729 %s: option `%s' requires an argument\n"),
730 argv[0], argv[optind - 1]) >= 0)
732 if (_IO_fwide (stderr, 0) > 0)
733 __fwprintf (stderr, L"%s", buf);
734 else
735 fputs (buf, stderr);
737 free (buf);
739 #else
740 fprintf (stderr,
741 _("%s: option `%s' requires an argument\n"),
742 argv[0], argv[optind - 1]);
743 #endif
745 nextchar += strlen (nextchar);
746 optopt = pfound->val;
747 return optstring[0] == ':' ? ':' : '?';
750 nextchar += strlen (nextchar);
751 if (longind != NULL)
752 *longind = option_index;
753 if (pfound->flag)
755 *(pfound->flag) = pfound->val;
756 return 0;
758 return pfound->val;
761 /* Can't find it as a long option. If this is not getopt_long_only,
762 or the option starts with '--' or is not a valid short
763 option, then it's an error.
764 Otherwise interpret it as a short option. */
765 if (!long_only || argv[optind][1] == '-'
766 || strchr (optstring, *nextchar) == NULL)
768 if (print_errors)
770 #if defined _LIBC && defined USE_IN_LIBIO
771 char *buf;
772 int n;
773 #endif
775 if (argv[optind][1] == '-')
777 /* --option */
778 #if defined _LIBC && defined USE_IN_LIBIO
779 n = __asprintf (&buf, _("%s: unrecognized option `--%s'\n"),
780 argv[0], nextchar);
781 #else
782 fprintf (stderr, _("%s: unrecognized option `--%s'\n"),
783 argv[0], nextchar);
784 #endif
786 else
788 /* +option or -option */
789 #if defined _LIBC && defined USE_IN_LIBIO
790 n = __asprintf (&buf, _("%s: unrecognized option `%c%s'\n"),
791 argv[0], argv[optind][0], nextchar);
792 #else
793 fprintf (stderr, _("%s: unrecognized option `%c%s'\n"),
794 argv[0], argv[optind][0], nextchar);
795 #endif
798 #if defined _LIBC && defined USE_IN_LIBIO
799 if (n >= 0)
801 if (_IO_fwide (stderr, 0) > 0)
802 __fwprintf (stderr, L"%s", buf);
803 else
804 fputs (buf, stderr);
806 free (buf);
808 #endif
810 nextchar = (char *) "";
811 optind++;
812 optopt = 0;
813 return '?';
817 /* Look at and handle the next short option-character. */
820 char c = *nextchar++;
821 char *temp = strchr (optstring, c);
823 /* Increment `optind' when we start to process its last character. */
824 if (*nextchar == '\0')
825 ++optind;
827 if (temp == NULL || c == ':')
829 if (print_errors)
831 #if defined _LIBC && defined USE_IN_LIBIO
832 char *buf;
833 int n;
834 #endif
836 if (posixly_correct)
838 /* 1003.2 specifies the format of this message. */
839 #if defined _LIBC && defined USE_IN_LIBIO
840 n = __asprintf (&buf, _("%s: illegal option -- %c\n"),
841 argv[0], c);
842 #else
843 fprintf (stderr, _("%s: illegal option -- %c\n"), argv[0], c);
844 #endif
846 else
848 #if defined _LIBC && defined USE_IN_LIBIO
849 n = __asprintf (&buf, _("%s: invalid option -- %c\n"),
850 argv[0], c);
851 #else
852 fprintf (stderr, _("%s: invalid option -- %c\n"), argv[0], c);
853 #endif
856 #if defined _LIBC && defined USE_IN_LIBIO
857 if (n >= 0)
859 if (_IO_fwide (stderr, 0) > 0)
860 __fwprintf (stderr, L"%s", buf);
861 else
862 fputs (buf, stderr);
864 free (buf);
866 #endif
868 optopt = c;
869 return '?';
871 /* Convenience. Treat POSIX -W foo same as long option --foo */
872 if (temp[0] == 'W' && temp[1] == ';')
874 char *nameend;
875 const struct option *p;
876 const struct option *pfound = NULL;
877 int exact = 0;
878 int ambig = 0;
879 int indfound = 0;
880 int option_index;
882 /* This is an option that requires an argument. */
883 if (*nextchar != '\0')
885 optarg = nextchar;
886 /* If we end this ARGV-element by taking the rest as an arg,
887 we must advance to the next element now. */
888 optind++;
890 else if (optind == argc)
892 if (print_errors)
894 /* 1003.2 specifies the format of this message. */
895 #if defined _LIBC && defined USE_IN_LIBIO
896 char *buf;
898 if (__asprintf (&buf,
899 _("%s: option requires an argument -- %c\n"),
900 argv[0], c) >= 0)
902 if (_IO_fwide (stderr, 0) > 0)
903 __fwprintf (stderr, L"%s", buf);
904 else
905 fputs (buf, stderr);
907 free (buf);
909 #else
910 fprintf (stderr, _("%s: option requires an argument -- %c\n"),
911 argv[0], c);
912 #endif
914 optopt = c;
915 if (optstring[0] == ':')
916 c = ':';
917 else
918 c = '?';
919 return c;
921 else
922 /* We already incremented `optind' once;
923 increment it again when taking next ARGV-elt as argument. */
924 optarg = argv[optind++];
926 /* optarg is now the argument, see if it's in the
927 table of longopts. */
929 for (nextchar = nameend = optarg; *nameend && *nameend != '='; nameend++)
930 /* Do nothing. */ ;
932 /* Test all long options for either exact match
933 or abbreviated matches. */
934 for (p = longopts, option_index = 0; p->name; p++, option_index++)
935 if (!strncmp (p->name, nextchar, nameend - nextchar))
937 if ((unsigned int) (nameend - nextchar) == strlen (p->name))
939 /* Exact match found. */
940 pfound = p;
941 indfound = option_index;
942 exact = 1;
943 break;
945 else if (pfound == NULL)
947 /* First nonexact match found. */
948 pfound = p;
949 indfound = option_index;
951 else
952 /* Second or later nonexact match found. */
953 ambig = 1;
955 if (ambig && !exact)
957 if (print_errors)
959 #if defined _LIBC && defined USE_IN_LIBIO
960 char *buf;
962 if (__asprintf (&buf, _("%s: option `-W %s' is ambiguous\n"),
963 argv[0], argv[optind]) >= 0)
965 if (_IO_fwide (stderr, 0) > 0)
966 __fwprintf (stderr, L"%s", buf);
967 else
968 fputs (buf, stderr);
970 free (buf);
972 #else
973 fprintf (stderr, _("%s: option `-W %s' is ambiguous\n"),
974 argv[0], argv[optind]);
975 #endif
977 nextchar += strlen (nextchar);
978 optind++;
979 return '?';
981 if (pfound != NULL)
983 option_index = indfound;
984 if (*nameend)
986 /* Don't test has_arg with >, because some C compilers don't
987 allow it to be used on enums. */
988 if (pfound->has_arg)
989 optarg = nameend + 1;
990 else
992 if (print_errors)
994 #if defined _LIBC && defined USE_IN_LIBIO
995 char *buf;
997 if (__asprintf (&buf, _("\
998 %s: option `-W %s' doesn't allow an argument\n"),
999 argv[0], pfound->name) >= 0)
1001 if (_IO_fwide (stderr, 0) > 0)
1002 __fwprintf (stderr, L"%s", buf);
1003 else
1004 fputs (buf, stderr);
1006 free (buf);
1008 #else
1009 fprintf (stderr, _("\
1010 %s: option `-W %s' doesn't allow an argument\n"),
1011 argv[0], pfound->name);
1012 #endif
1015 nextchar += strlen (nextchar);
1016 return '?';
1019 else if (pfound->has_arg == 1)
1021 if (optind < argc)
1022 optarg = argv[optind++];
1023 else
1025 if (print_errors)
1027 #if defined _LIBC && defined USE_IN_LIBIO
1028 char *buf;
1030 if (__asprintf (&buf, _("\
1031 %s: option `%s' requires an argument\n"),
1032 argv[0], argv[optind - 1]) >= 0)
1034 if (_IO_fwide (stderr, 0) > 0)
1035 __fwprintf (stderr, L"%s", buf);
1036 else
1037 fputs (buf, stderr);
1039 free (buf);
1041 #else
1042 fprintf (stderr,
1043 _("%s: option `%s' requires an argument\n"),
1044 argv[0], argv[optind - 1]);
1045 #endif
1047 nextchar += strlen (nextchar);
1048 return optstring[0] == ':' ? ':' : '?';
1051 nextchar += strlen (nextchar);
1052 if (longind != NULL)
1053 *longind = option_index;
1054 if (pfound->flag)
1056 *(pfound->flag) = pfound->val;
1057 return 0;
1059 return pfound->val;
1061 nextchar = NULL;
1062 return 'W'; /* Let the application handle it. */
1064 if (temp[1] == ':')
1066 if (temp[2] == ':')
1068 /* This is an option that accepts an argument optionally. */
1069 if (*nextchar != '\0')
1071 optarg = nextchar;
1072 optind++;
1074 else
1075 optarg = NULL;
1076 nextchar = NULL;
1078 else
1080 /* This is an option that requires an argument. */
1081 if (*nextchar != '\0')
1083 optarg = nextchar;
1084 /* If we end this ARGV-element by taking the rest as an arg,
1085 we must advance to the next element now. */
1086 optind++;
1088 else if (optind == argc)
1090 if (print_errors)
1092 /* 1003.2 specifies the format of this message. */
1093 #if defined _LIBC && defined USE_IN_LIBIO
1094 char *buf;
1096 if (__asprintf (&buf, _("\
1097 %s: option requires an argument -- %c\n"),
1098 argv[0], c) >= 0)
1100 if (_IO_fwide (stderr, 0) > 0)
1101 __fwprintf (stderr, L"%s", buf);
1102 else
1103 fputs (buf, stderr);
1105 free (buf);
1107 #else
1108 fprintf (stderr,
1109 _("%s: option requires an argument -- %c\n"),
1110 argv[0], c);
1111 #endif
1113 optopt = c;
1114 if (optstring[0] == ':')
1115 c = ':';
1116 else
1117 c = '?';
1119 else
1120 /* We already incremented `optind' once;
1121 increment it again when taking next ARGV-elt as argument. */
1122 optarg = argv[optind++];
1123 nextchar = NULL;
1126 return c;
1131 getopt (int argc, char *const *argv, const char *optstring)
1133 return _getopt_internal (argc, argv, optstring,
1134 (const struct option *) 0,
1135 (int *) 0,
1139 #endif /* Not ELIDE_CODE. */
1141 #ifdef TEST
1143 /* Compile with -DTEST to make an executable for use in testing
1144 the above definition of `getopt'. */
1147 main (int argc, char **argv)
1149 int c;
1150 int digit_optind = 0;
1152 while (1)
1154 int this_option_optind = optind ? optind : 1;
1156 c = getopt (argc, argv, "abc:d:0123456789");
1157 if (c == -1)
1158 break;
1160 switch (c)
1162 case '0':
1163 case '1':
1164 case '2':
1165 case '3':
1166 case '4':
1167 case '5':
1168 case '6':
1169 case '7':
1170 case '8':
1171 case '9':
1172 if (digit_optind != 0 && digit_optind != this_option_optind)
1173 printf ("digits occur in two different argv-elements.\n");
1174 digit_optind = this_option_optind;
1175 printf ("option %c\n", c);
1176 break;
1178 case 'a':
1179 printf ("option a\n");
1180 break;
1182 case 'b':
1183 printf ("option b\n");
1184 break;
1186 case 'c':
1187 printf ("option c with value `%s'\n", optarg);
1188 break;
1190 case '?':
1191 break;
1193 default:
1194 printf ("?? getopt returned character code 0%o ??\n", c);
1198 if (optind < argc)
1200 printf ("non-option ARGV-elements: ");
1201 while (optind < argc)
1202 printf ("%s ", argv[optind++]);
1203 printf ("\n");
1206 exit (0);
1209 #endif /* TEST */