Fix test_compress.sh.
[lzma-utils.git] / lib / getopt.c
blob1d14b245b2b683c0952a298108dad73d334eb8f9
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,2006
6 Free Software Foundation, Inc.
7 This file is part of the GNU C Library.
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU Lesser General Public License as published by
11 the Free Software Foundation; either version 2.1, or (at your option)
12 any later version.
14 This program 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
17 GNU Lesser General Public License for more details.
19 You should have received a copy of the GNU Lesser General Public License along
20 with this program; if not, write to the Free Software Foundation,
21 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
23 #ifndef _LIBC
24 # include <config.h>
25 #endif
27 #include "getopt.h"
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <unistd.h>
34 #ifdef __VMS
35 # include <unixlib.h>
36 #endif
38 /* Completely disable NLS for getopt. We won't include translations for it
39 anyway. If the system lacks getopt_long, missing translations probably
40 aren't a problem. */
42 #ifdef _LIBC
43 # include <libintl.h>
44 #else
45 # include "gettext.h"
46 # define _(msgid) gettext (msgid)
47 #endif
49 #define _(msgid) (msgid)
51 #if defined _LIBC && defined USE_IN_LIBIO
52 # include <wchar.h>
53 #endif
55 #ifndef attribute_hidden
56 # define attribute_hidden
57 #endif
59 /* Unlike standard Unix `getopt', functions like `getopt_long'
60 let the user intersperse the options with the other arguments.
62 As `getopt_long' works, it permutes the elements of ARGV so that,
63 when it is done, all the options precede everything else. Thus
64 all application programs are extended to handle flexible argument order.
66 Using `getopt' or setting the environment variable POSIXLY_CORRECT
67 disables permutation.
68 Then the application's behavior is completely standard.
70 GNU application programs can use a third alternative mode in which
71 they can distinguish the relative order of options and other arguments. */
73 #include "getopt_int.h"
75 /* For communication from `getopt' to the caller.
76 When `getopt' finds an option that takes an argument,
77 the argument value is returned here.
78 Also, when `ordering' is RETURN_IN_ORDER,
79 each non-option ARGV-element is returned here. */
81 char *optarg;
83 /* Index in ARGV of the next element to be scanned.
84 This is used for communication to and from the caller
85 and for communication between successive calls to `getopt'.
87 On entry to `getopt', zero means this is the first call; initialize.
89 When `getopt' returns -1, this is the index of the first of the
90 non-option elements that the caller should itself scan.
92 Otherwise, `optind' communicates from one call to the next
93 how much of ARGV has been scanned so far. */
95 /* 1003.2 says this must be 1 before any call. */
96 int optind = 1;
98 /* Callers store zero here to inhibit the error message
99 for unrecognized options. */
101 int opterr = 1;
103 /* Set to an option character which was unrecognized.
104 This must be initialized on some systems to avoid linking in the
105 system's own getopt implementation. */
107 int optopt = '?';
109 /* Keep a global copy of all internal members of getopt_data. */
111 static struct _getopt_data getopt_data;
114 #if defined HAVE_DECL_GETENV && !HAVE_DECL_GETENV
115 extern char *getenv ();
116 #endif
118 #ifdef _LIBC
119 /* Stored original parameters.
120 XXX This is no good solution. We should rather copy the args so
121 that we can compare them later. But we must not use malloc(3). */
122 extern int __libc_argc;
123 extern char **__libc_argv;
125 /* Bash 2.0 gives us an environment variable containing flags
126 indicating ARGV elements that should not be considered arguments. */
128 # ifdef USE_NONOPTION_FLAGS
129 /* Defined in getopt_init.c */
130 extern char *__getopt_nonoption_flags;
131 # endif
133 # ifdef USE_NONOPTION_FLAGS
134 # define SWAP_FLAGS(ch1, ch2) \
135 if (d->__nonoption_flags_len > 0) \
137 char __tmp = __getopt_nonoption_flags[ch1]; \
138 __getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2]; \
139 __getopt_nonoption_flags[ch2] = __tmp; \
141 # else
142 # define SWAP_FLAGS(ch1, ch2)
143 # endif
144 #else /* !_LIBC */
145 # define SWAP_FLAGS(ch1, ch2)
146 #endif /* _LIBC */
148 /* Exchange two adjacent subsequences of ARGV.
149 One subsequence is elements [first_nonopt,last_nonopt)
150 which contains all the non-options that have been skipped so far.
151 The other is elements [last_nonopt,optind), which contains all
152 the options processed since those non-options were skipped.
154 `first_nonopt' and `last_nonopt' are relocated so that they describe
155 the new indices of the non-options in ARGV after they are moved. */
157 static void
158 exchange (char **argv, struct _getopt_data *d)
160 int bottom = d->__first_nonopt;
161 int middle = d->__last_nonopt;
162 int top = d->optind;
163 char *tem;
165 /* Exchange the shorter segment with the far end of the longer segment.
166 That puts the shorter segment into the right place.
167 It leaves the longer segment in the right place overall,
168 but it consists of two parts that need to be swapped next. */
170 #if defined _LIBC && defined USE_NONOPTION_FLAGS
171 /* First make sure the handling of the `__getopt_nonoption_flags'
172 string can work normally. Our top argument must be in the range
173 of the string. */
174 if (d->__nonoption_flags_len > 0 && top >= d->__nonoption_flags_max_len)
176 /* We must extend the array. The user plays games with us and
177 presents new arguments. */
178 char *new_str = malloc (top + 1);
179 if (new_str == NULL)
180 d->__nonoption_flags_len = d->__nonoption_flags_max_len = 0;
181 else
183 memset (__mempcpy (new_str, __getopt_nonoption_flags,
184 d->__nonoption_flags_max_len),
185 '\0', top + 1 - d->__nonoption_flags_max_len);
186 d->__nonoption_flags_max_len = top + 1;
187 __getopt_nonoption_flags = new_str;
190 #endif
192 while (top > middle && middle > bottom)
194 if (top - middle > middle - bottom)
196 /* Bottom segment is the short one. */
197 int len = middle - bottom;
198 register int i;
200 /* Swap it with the top part of the top segment. */
201 for (i = 0; i < len; i++)
203 tem = argv[bottom + i];
204 argv[bottom + i] = argv[top - (middle - bottom) + i];
205 argv[top - (middle - bottom) + i] = tem;
206 SWAP_FLAGS (bottom + i, top - (middle - bottom) + i);
208 /* Exclude the moved bottom segment from further swapping. */
209 top -= len;
211 else
213 /* Top segment is the short one. */
214 int len = top - middle;
215 register int i;
217 /* Swap it with the bottom part of the bottom segment. */
218 for (i = 0; i < len; i++)
220 tem = argv[bottom + i];
221 argv[bottom + i] = argv[middle + i];
222 argv[middle + i] = tem;
223 SWAP_FLAGS (bottom + i, middle + i);
225 /* Exclude the moved top segment from further swapping. */
226 bottom += len;
230 /* Update records for the slots the non-options now occupy. */
232 d->__first_nonopt += (d->optind - d->__last_nonopt);
233 d->__last_nonopt = d->optind;
236 /* Initialize the internal data when the first call is made. */
238 static const char *
239 _getopt_initialize (int argc, char **argv, const char *optstring,
240 int posixly_correct, struct _getopt_data *d)
242 /* Start processing options with ARGV-element 1 (since ARGV-element 0
243 is the program name); the sequence of previously skipped
244 non-option ARGV-elements is empty. */
246 d->__first_nonopt = d->__last_nonopt = d->optind;
248 d->__nextchar = NULL;
250 d->__posixly_correct = posixly_correct || !!getenv ("POSIXLY_CORRECT");
252 /* Determine how to handle the ordering of options and nonoptions. */
254 if (optstring[0] == '-')
256 d->__ordering = RETURN_IN_ORDER;
257 ++optstring;
259 else if (optstring[0] == '+')
261 d->__ordering = REQUIRE_ORDER;
262 ++optstring;
264 else if (d->__posixly_correct)
265 d->__ordering = REQUIRE_ORDER;
266 else
267 d->__ordering = PERMUTE;
269 #if defined _LIBC && defined USE_NONOPTION_FLAGS
270 if (!d->__posixly_correct
271 && argc == __libc_argc && argv == __libc_argv)
273 if (d->__nonoption_flags_max_len == 0)
275 if (__getopt_nonoption_flags == NULL
276 || __getopt_nonoption_flags[0] == '\0')
277 d->__nonoption_flags_max_len = -1;
278 else
280 const char *orig_str = __getopt_nonoption_flags;
281 int len = d->__nonoption_flags_max_len = strlen (orig_str);
282 if (d->__nonoption_flags_max_len < argc)
283 d->__nonoption_flags_max_len = argc;
284 __getopt_nonoption_flags =
285 (char *) malloc (d->__nonoption_flags_max_len);
286 if (__getopt_nonoption_flags == NULL)
287 d->__nonoption_flags_max_len = -1;
288 else
289 memset (__mempcpy (__getopt_nonoption_flags, orig_str, len),
290 '\0', d->__nonoption_flags_max_len - len);
293 d->__nonoption_flags_len = d->__nonoption_flags_max_len;
295 else
296 d->__nonoption_flags_len = 0;
297 #endif
299 return optstring;
302 /* Scan elements of ARGV (whose length is ARGC) for option characters
303 given in OPTSTRING.
305 If an element of ARGV starts with '-', and is not exactly "-" or "--",
306 then it is an option element. The characters of this element
307 (aside from the initial '-') are option characters. If `getopt'
308 is called repeatedly, it returns successively each of the option characters
309 from each of the option elements.
311 If `getopt' finds another option character, it returns that character,
312 updating `optind' and `nextchar' so that the next call to `getopt' can
313 resume the scan with the following option character or ARGV-element.
315 If there are no more option characters, `getopt' returns -1.
316 Then `optind' is the index in ARGV of the first ARGV-element
317 that is not an option. (The ARGV-elements have been permuted
318 so that those that are not options now come last.)
320 OPTSTRING is a string containing the legitimate option characters.
321 If an option character is seen that is not listed in OPTSTRING,
322 return '?' after printing an error message. If you set `opterr' to
323 zero, the error message is suppressed but we still return '?'.
325 If a char in OPTSTRING is followed by a colon, that means it wants an arg,
326 so the following text in the same ARGV-element, or the text of the following
327 ARGV-element, is returned in `optarg'. Two colons mean an option that
328 wants an optional arg; if there is text in the current ARGV-element,
329 it is returned in `optarg', otherwise `optarg' is set to zero.
331 If OPTSTRING starts with `-' or `+', it requests different methods of
332 handling the non-option ARGV-elements.
333 See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
335 Long-named options begin with `--' instead of `-'.
336 Their names may be abbreviated as long as the abbreviation is unique
337 or is an exact match for some defined option. If they have an
338 argument, it follows the option name in the same ARGV-element, separated
339 from the option name by a `=', or else the in next ARGV-element.
340 When `getopt' finds a long-named option, it returns 0 if that option's
341 `flag' field is nonzero, the value of the option's `val' field
342 if the `flag' field is zero.
344 LONGOPTS is a vector of `struct option' terminated by an
345 element containing a name which is zero.
347 LONGIND returns the index in LONGOPT of the long-named option found.
348 It is only valid when a long-named option has been found by the most
349 recent call.
351 If LONG_ONLY is nonzero, '-' as well as '--' can introduce
352 long-named options.
354 If POSIXLY_CORRECT is nonzero, behave as if the POSIXLY_CORRECT
355 environment variable were set. */
358 _getopt_internal_r (int argc, char **argv, const char *optstring,
359 const struct option *longopts, int *longind,
360 int long_only, int posixly_correct, struct _getopt_data *d)
362 int print_errors = d->opterr;
363 if (optstring[0] == ':')
364 print_errors = 0;
366 if (argc < 1)
367 return -1;
369 d->optarg = NULL;
371 if (d->optind == 0 || !d->__initialized)
373 if (d->optind == 0)
374 d->optind = 1; /* Don't scan ARGV[0], the program name. */
375 optstring = _getopt_initialize (argc, argv, optstring,
376 posixly_correct, d);
377 d->__initialized = 1;
380 /* Test whether ARGV[optind] points to a non-option argument.
381 Either it does not have option syntax, or there is an environment flag
382 from the shell indicating it is not an option. The later information
383 is only used when the used in the GNU libc. */
384 #if defined _LIBC && defined USE_NONOPTION_FLAGS
385 # define NONOPTION_P (argv[d->optind][0] != '-' || argv[d->optind][1] == '\0' \
386 || (d->optind < d->__nonoption_flags_len \
387 && __getopt_nonoption_flags[d->optind] == '1'))
388 #else
389 # define NONOPTION_P (argv[d->optind][0] != '-' || argv[d->optind][1] == '\0')
390 #endif
392 if (d->__nextchar == NULL || *d->__nextchar == '\0')
394 /* Advance to the next ARGV-element. */
396 /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
397 moved back by the user (who may also have changed the arguments). */
398 if (d->__last_nonopt > d->optind)
399 d->__last_nonopt = d->optind;
400 if (d->__first_nonopt > d->optind)
401 d->__first_nonopt = d->optind;
403 if (d->__ordering == PERMUTE)
405 /* If we have just processed some options following some non-options,
406 exchange them so that the options come first. */
408 if (d->__first_nonopt != d->__last_nonopt
409 && d->__last_nonopt != d->optind)
410 exchange ((char **) argv, d);
411 else if (d->__last_nonopt != d->optind)
412 d->__first_nonopt = d->optind;
414 /* Skip any additional non-options
415 and extend the range of non-options previously skipped. */
417 while (d->optind < argc && NONOPTION_P)
418 d->optind++;
419 d->__last_nonopt = d->optind;
422 /* The special ARGV-element `--' means premature end of options.
423 Skip it like a null option,
424 then exchange with previous non-options as if it were an option,
425 then skip everything else like a non-option. */
427 if (d->optind != argc && !strcmp (argv[d->optind], "--"))
429 d->optind++;
431 if (d->__first_nonopt != d->__last_nonopt
432 && d->__last_nonopt != d->optind)
433 exchange ((char **) argv, d);
434 else if (d->__first_nonopt == d->__last_nonopt)
435 d->__first_nonopt = d->optind;
436 d->__last_nonopt = argc;
438 d->optind = argc;
441 /* If we have done all the ARGV-elements, stop the scan
442 and back over any non-options that we skipped and permuted. */
444 if (d->optind == argc)
446 /* Set the next-arg-index to point at the non-options
447 that we previously skipped, so the caller will digest them. */
448 if (d->__first_nonopt != d->__last_nonopt)
449 d->optind = d->__first_nonopt;
450 return -1;
453 /* If we have come to a non-option and did not permute it,
454 either stop the scan or describe it to the caller and pass it by. */
456 if (NONOPTION_P)
458 if (d->__ordering == REQUIRE_ORDER)
459 return -1;
460 d->optarg = argv[d->optind++];
461 return 1;
464 /* We have found another option-ARGV-element.
465 Skip the initial punctuation. */
467 d->__nextchar = (argv[d->optind] + 1
468 + (longopts != NULL && argv[d->optind][1] == '-'));
471 /* Decode the current option-ARGV-element. */
473 /* Check whether the ARGV-element is a long option.
475 If long_only and the ARGV-element has the form "-f", where f is
476 a valid short option, don't consider it an abbreviated form of
477 a long option that starts with f. Otherwise there would be no
478 way to give the -f short option.
480 On the other hand, if there's a long option "fubar" and
481 the ARGV-element is "-fu", do consider that an abbreviation of
482 the long option, just like "--fu", and not "-f" with arg "u".
484 This distinction seems to be the most useful approach. */
486 if (longopts != NULL
487 && (argv[d->optind][1] == '-'
488 || (long_only && (argv[d->optind][2]
489 || !strchr (optstring, argv[d->optind][1])))))
491 char *nameend;
492 const struct option *p;
493 const struct option *pfound = NULL;
494 int exact = 0;
495 int ambig = 0;
496 int indfound = -1;
497 int option_index;
499 for (nameend = d->__nextchar; *nameend && *nameend != '='; nameend++)
500 /* Do nothing. */ ;
502 /* Test all long options for either exact match
503 or abbreviated matches. */
504 for (p = longopts, option_index = 0; p->name; p++, option_index++)
505 if (!strncmp (p->name, d->__nextchar, nameend - d->__nextchar))
507 if ((unsigned int) (nameend - d->__nextchar)
508 == (unsigned int) strlen (p->name))
510 /* Exact match found. */
511 pfound = p;
512 indfound = option_index;
513 exact = 1;
514 break;
516 else if (pfound == NULL)
518 /* First nonexact match found. */
519 pfound = p;
520 indfound = option_index;
522 else if (long_only
523 || pfound->has_arg != p->has_arg
524 || pfound->flag != p->flag
525 || pfound->val != p->val)
526 /* Second or later nonexact match found. */
527 ambig = 1;
530 if (ambig && !exact)
532 if (print_errors)
534 #if defined _LIBC && defined USE_IN_LIBIO
535 char *buf;
537 if (__asprintf (&buf, _("%s: option `%s' is ambiguous\n"),
538 argv[0], argv[d->optind]) >= 0)
540 _IO_flockfile (stderr);
542 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
543 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
545 __fxprintf (NULL, "%s", buf);
547 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
548 _IO_funlockfile (stderr);
550 free (buf);
552 #else
553 fprintf (stderr, _("%s: option `%s' is ambiguous\n"),
554 argv[0], argv[d->optind]);
555 #endif
557 d->__nextchar += strlen (d->__nextchar);
558 d->optind++;
559 d->optopt = 0;
560 return '?';
563 if (pfound != NULL)
565 option_index = indfound;
566 d->optind++;
567 if (*nameend)
569 /* Don't test has_arg with >, because some C compilers don't
570 allow it to be used on enums. */
571 if (pfound->has_arg)
572 d->optarg = nameend + 1;
573 else
575 if (print_errors)
577 #if defined _LIBC && defined USE_IN_LIBIO
578 char *buf;
579 int n;
580 #endif
582 if (argv[d->optind - 1][1] == '-')
584 /* --option */
585 #if defined _LIBC && defined USE_IN_LIBIO
586 n = __asprintf (&buf, _("\
587 %s: option `--%s' doesn't allow an argument\n"),
588 argv[0], pfound->name);
589 #else
590 fprintf (stderr, _("\
591 %s: option `--%s' doesn't allow an argument\n"),
592 argv[0], pfound->name);
593 #endif
595 else
597 /* +option or -option */
598 #if defined _LIBC && defined USE_IN_LIBIO
599 n = __asprintf (&buf, _("\
600 %s: option `%c%s' doesn't allow an argument\n"),
601 argv[0], argv[d->optind - 1][0],
602 pfound->name);
603 #else
604 fprintf (stderr, _("\
605 %s: option `%c%s' doesn't allow an argument\n"),
606 argv[0], argv[d->optind - 1][0],
607 pfound->name);
608 #endif
611 #if defined _LIBC && defined USE_IN_LIBIO
612 if (n >= 0)
614 _IO_flockfile (stderr);
616 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
617 ((_IO_FILE *) stderr)->_flags2
618 |= _IO_FLAGS2_NOTCANCEL;
620 __fxprintf (NULL, "%s", buf);
622 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
623 _IO_funlockfile (stderr);
625 free (buf);
627 #endif
630 d->__nextchar += strlen (d->__nextchar);
632 d->optopt = pfound->val;
633 return '?';
636 else if (pfound->has_arg == 1)
638 if (d->optind < argc)
639 d->optarg = argv[d->optind++];
640 else
642 if (print_errors)
644 #if defined _LIBC && defined USE_IN_LIBIO
645 char *buf;
647 if (__asprintf (&buf, _("\
648 %s: option `%s' requires an argument\n"),
649 argv[0], argv[d->optind - 1]) >= 0)
651 _IO_flockfile (stderr);
653 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
654 ((_IO_FILE *) stderr)->_flags2
655 |= _IO_FLAGS2_NOTCANCEL;
657 __fxprintf (NULL, "%s", buf);
659 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
660 _IO_funlockfile (stderr);
662 free (buf);
664 #else
665 fprintf (stderr,
666 _("%s: option `%s' requires an argument\n"),
667 argv[0], argv[d->optind - 1]);
668 #endif
670 d->__nextchar += strlen (d->__nextchar);
671 d->optopt = pfound->val;
672 return optstring[0] == ':' ? ':' : '?';
675 d->__nextchar += strlen (d->__nextchar);
676 if (longind != NULL)
677 *longind = option_index;
678 if (pfound->flag)
680 *(pfound->flag) = pfound->val;
681 return 0;
683 return pfound->val;
686 /* Can't find it as a long option. If this is not getopt_long_only,
687 or the option starts with '--' or is not a valid short
688 option, then it's an error.
689 Otherwise interpret it as a short option. */
690 if (!long_only || argv[d->optind][1] == '-'
691 || strchr (optstring, *d->__nextchar) == NULL)
693 if (print_errors)
695 #if defined _LIBC && defined USE_IN_LIBIO
696 char *buf;
697 int n;
698 #endif
700 if (argv[d->optind][1] == '-')
702 /* --option */
703 #if defined _LIBC && defined USE_IN_LIBIO
704 n = __asprintf (&buf, _("%s: unrecognized option `--%s'\n"),
705 argv[0], d->__nextchar);
706 #else
707 fprintf (stderr, _("%s: unrecognized option `--%s'\n"),
708 argv[0], d->__nextchar);
709 #endif
711 else
713 /* +option or -option */
714 #if defined _LIBC && defined USE_IN_LIBIO
715 n = __asprintf (&buf, _("%s: unrecognized option `%c%s'\n"),
716 argv[0], argv[d->optind][0], d->__nextchar);
717 #else
718 fprintf (stderr, _("%s: unrecognized option `%c%s'\n"),
719 argv[0], argv[d->optind][0], d->__nextchar);
720 #endif
723 #if defined _LIBC && defined USE_IN_LIBIO
724 if (n >= 0)
726 _IO_flockfile (stderr);
728 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
729 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
731 __fxprintf (NULL, "%s", buf);
733 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
734 _IO_funlockfile (stderr);
736 free (buf);
738 #endif
740 d->__nextchar = (char *) "";
741 d->optind++;
742 d->optopt = 0;
743 return '?';
747 /* Look at and handle the next short option-character. */
750 char c = *d->__nextchar++;
751 char *temp = strchr (optstring, c);
753 /* Increment `optind' when we start to process its last character. */
754 if (*d->__nextchar == '\0')
755 ++d->optind;
757 if (temp == NULL || c == ':')
759 if (print_errors)
761 #if defined _LIBC && defined USE_IN_LIBIO
762 char *buf;
763 int n;
764 #endif
766 if (d->__posixly_correct)
768 /* 1003.2 specifies the format of this message. */
769 #if defined _LIBC && defined USE_IN_LIBIO
770 n = __asprintf (&buf, _("%s: illegal option -- %c\n"),
771 argv[0], c);
772 #else
773 fprintf (stderr, _("%s: illegal option -- %c\n"), argv[0], c);
774 #endif
776 else
778 #if defined _LIBC && defined USE_IN_LIBIO
779 n = __asprintf (&buf, _("%s: invalid option -- %c\n"),
780 argv[0], c);
781 #else
782 fprintf (stderr, _("%s: invalid option -- %c\n"), argv[0], c);
783 #endif
786 #if defined _LIBC && defined USE_IN_LIBIO
787 if (n >= 0)
789 _IO_flockfile (stderr);
791 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
792 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
794 __fxprintf (NULL, "%s", buf);
796 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
797 _IO_funlockfile (stderr);
799 free (buf);
801 #endif
803 d->optopt = c;
804 return '?';
806 /* Convenience. Treat POSIX -W foo same as long option --foo */
807 if (temp[0] == 'W' && temp[1] == ';')
809 char *nameend;
810 const struct option *p;
811 const struct option *pfound = NULL;
812 int exact = 0;
813 int ambig = 0;
814 int indfound = 0;
815 int option_index;
817 /* This is an option that requires an argument. */
818 if (*d->__nextchar != '\0')
820 d->optarg = d->__nextchar;
821 /* If we end this ARGV-element by taking the rest as an arg,
822 we must advance to the next element now. */
823 d->optind++;
825 else if (d->optind == argc)
827 if (print_errors)
829 /* 1003.2 specifies the format of this message. */
830 #if defined _LIBC && defined USE_IN_LIBIO
831 char *buf;
833 if (__asprintf (&buf,
834 _("%s: option requires an argument -- %c\n"),
835 argv[0], c) >= 0)
837 _IO_flockfile (stderr);
839 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
840 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
842 __fxprintf (NULL, "%s", buf);
844 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
845 _IO_funlockfile (stderr);
847 free (buf);
849 #else
850 fprintf (stderr, _("%s: option requires an argument -- %c\n"),
851 argv[0], c);
852 #endif
854 d->optopt = c;
855 if (optstring[0] == ':')
856 c = ':';
857 else
858 c = '?';
859 return c;
861 else
862 /* We already incremented `d->optind' once;
863 increment it again when taking next ARGV-elt as argument. */
864 d->optarg = argv[d->optind++];
866 /* optarg is now the argument, see if it's in the
867 table of longopts. */
869 for (d->__nextchar = nameend = d->optarg; *nameend && *nameend != '=';
870 nameend++)
871 /* Do nothing. */ ;
873 /* Test all long options for either exact match
874 or abbreviated matches. */
875 for (p = longopts, option_index = 0; p->name; p++, option_index++)
876 if (!strncmp (p->name, d->__nextchar, nameend - d->__nextchar))
878 if ((unsigned int) (nameend - d->__nextchar) == strlen (p->name))
880 /* Exact match found. */
881 pfound = p;
882 indfound = option_index;
883 exact = 1;
884 break;
886 else if (pfound == NULL)
888 /* First nonexact match found. */
889 pfound = p;
890 indfound = option_index;
892 else
893 /* Second or later nonexact match found. */
894 ambig = 1;
896 if (ambig && !exact)
898 if (print_errors)
900 #if defined _LIBC && defined USE_IN_LIBIO
901 char *buf;
903 if (__asprintf (&buf, _("%s: option `-W %s' is ambiguous\n"),
904 argv[0], argv[d->optind]) >= 0)
906 _IO_flockfile (stderr);
908 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
909 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
911 __fxprintf (NULL, "%s", buf);
913 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
914 _IO_funlockfile (stderr);
916 free (buf);
918 #else
919 fprintf (stderr, _("%s: option `-W %s' is ambiguous\n"),
920 argv[0], argv[d->optind]);
921 #endif
923 d->__nextchar += strlen (d->__nextchar);
924 d->optind++;
925 return '?';
927 if (pfound != NULL)
929 option_index = indfound;
930 if (*nameend)
932 /* Don't test has_arg with >, because some C compilers don't
933 allow it to be used on enums. */
934 if (pfound->has_arg)
935 d->optarg = nameend + 1;
936 else
938 if (print_errors)
940 #if defined _LIBC && defined USE_IN_LIBIO
941 char *buf;
943 if (__asprintf (&buf, _("\
944 %s: option `-W %s' doesn't allow an argument\n"),
945 argv[0], pfound->name) >= 0)
947 _IO_flockfile (stderr);
949 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
950 ((_IO_FILE *) stderr)->_flags2
951 |= _IO_FLAGS2_NOTCANCEL;
953 __fxprintf (NULL, "%s", buf);
955 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
956 _IO_funlockfile (stderr);
958 free (buf);
960 #else
961 fprintf (stderr, _("\
962 %s: option `-W %s' doesn't allow an argument\n"),
963 argv[0], pfound->name);
964 #endif
967 d->__nextchar += strlen (d->__nextchar);
968 return '?';
971 else if (pfound->has_arg == 1)
973 if (d->optind < argc)
974 d->optarg = argv[d->optind++];
975 else
977 if (print_errors)
979 #if defined _LIBC && defined USE_IN_LIBIO
980 char *buf;
982 if (__asprintf (&buf, _("\
983 %s: option `%s' requires an argument\n"),
984 argv[0], argv[d->optind - 1]) >= 0)
986 _IO_flockfile (stderr);
988 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
989 ((_IO_FILE *) stderr)->_flags2
990 |= _IO_FLAGS2_NOTCANCEL;
992 __fxprintf (NULL, "%s", buf);
994 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
995 _IO_funlockfile (stderr);
997 free (buf);
999 #else
1000 fprintf (stderr,
1001 _("%s: option `%s' requires an argument\n"),
1002 argv[0], argv[d->optind - 1]);
1003 #endif
1005 d->__nextchar += strlen (d->__nextchar);
1006 return optstring[0] == ':' ? ':' : '?';
1009 d->__nextchar += strlen (d->__nextchar);
1010 if (longind != NULL)
1011 *longind = option_index;
1012 if (pfound->flag)
1014 *(pfound->flag) = pfound->val;
1015 return 0;
1017 return pfound->val;
1019 d->__nextchar = NULL;
1020 return 'W'; /* Let the application handle it. */
1022 if (temp[1] == ':')
1024 if (temp[2] == ':')
1026 /* This is an option that accepts an argument optionally. */
1027 if (*d->__nextchar != '\0')
1029 d->optarg = d->__nextchar;
1030 d->optind++;
1032 else
1033 d->optarg = NULL;
1034 d->__nextchar = NULL;
1036 else
1038 /* This is an option that requires an argument. */
1039 if (*d->__nextchar != '\0')
1041 d->optarg = d->__nextchar;
1042 /* If we end this ARGV-element by taking the rest as an arg,
1043 we must advance to the next element now. */
1044 d->optind++;
1046 else if (d->optind == argc)
1048 if (print_errors)
1050 /* 1003.2 specifies the format of this message. */
1051 #if defined _LIBC && defined USE_IN_LIBIO
1052 char *buf;
1054 if (__asprintf (&buf, _("\
1055 %s: option requires an argument -- %c\n"),
1056 argv[0], c) >= 0)
1058 _IO_flockfile (stderr);
1060 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
1061 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
1063 __fxprintf (NULL, "%s", buf);
1065 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
1066 _IO_funlockfile (stderr);
1068 free (buf);
1070 #else
1071 fprintf (stderr,
1072 _("%s: option requires an argument -- %c\n"),
1073 argv[0], c);
1074 #endif
1076 d->optopt = c;
1077 if (optstring[0] == ':')
1078 c = ':';
1079 else
1080 c = '?';
1082 else
1083 /* We already incremented `optind' once;
1084 increment it again when taking next ARGV-elt as argument. */
1085 d->optarg = argv[d->optind++];
1086 d->__nextchar = NULL;
1089 return c;
1094 _getopt_internal (int argc, char **argv, const char *optstring,
1095 const struct option *longopts, int *longind,
1096 int long_only, int posixly_correct)
1098 int result;
1100 getopt_data.optind = optind;
1101 getopt_data.opterr = opterr;
1103 result = _getopt_internal_r (argc, argv, optstring, longopts, longind,
1104 long_only, posixly_correct, &getopt_data);
1106 optind = getopt_data.optind;
1107 optarg = getopt_data.optarg;
1108 optopt = getopt_data.optopt;
1110 return result;
1113 /* glibc gets a LSB-compliant getopt.
1114 Standalone applications get a POSIX-compliant getopt. */
1115 #if _LIBC
1116 enum { POSIXLY_CORRECT = 0 };
1117 #else
1118 enum { POSIXLY_CORRECT = 1 };
1119 #endif
1122 getopt (int argc, char *const *argv, const char *optstring)
1124 return _getopt_internal (argc, (char **) argv, optstring, NULL, NULL, 0,
1125 POSIXLY_CORRECT);
1129 #ifdef TEST
1131 /* Compile with -DTEST to make an executable for use in testing
1132 the above definition of `getopt'. */
1135 main (int argc, char **argv)
1137 int c;
1138 int digit_optind = 0;
1140 while (1)
1142 int this_option_optind = optind ? optind : 1;
1144 c = getopt (argc, argv, "abc:d:0123456789");
1145 if (c == -1)
1146 break;
1148 switch (c)
1150 case '0':
1151 case '1':
1152 case '2':
1153 case '3':
1154 case '4':
1155 case '5':
1156 case '6':
1157 case '7':
1158 case '8':
1159 case '9':
1160 if (digit_optind != 0 && digit_optind != this_option_optind)
1161 printf ("digits occur in two different argv-elements.\n");
1162 digit_optind = this_option_optind;
1163 printf ("option %c\n", c);
1164 break;
1166 case 'a':
1167 printf ("option a\n");
1168 break;
1170 case 'b':
1171 printf ("option b\n");
1172 break;
1174 case 'c':
1175 printf ("option c with value `%s'\n", optarg);
1176 break;
1178 case '?':
1179 break;
1181 default:
1182 printf ("?? getopt returned character code 0%o ??\n", c);
1186 if (optind < argc)
1188 printf ("non-option ARGV-elements: ");
1189 while (optind < argc)
1190 printf ("%s ", argv[optind++]);
1191 printf ("\n");
1194 exit (0);
1197 #endif /* TEST */