VirtualBox

source: kBuild/trunk/src/sed/lib/getopt.c@ 1294

Last change on this file since 1294 was 802, checked in by bird, 18 years ago

msvcrt build.

File size: 29.5 KB
Line 
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 [email protected]
4 before changing it!
5
6 Copyright (C) 1987, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98
7 Free Software Foundation, Inc.
8
9 NOTE: The canonical source of this file is maintained with the GNU C Library.
10 Bugs can be reported to [email protected].
11
12 This program is free software; you can redistribute it and/or modify it
13 under the terms of the GNU General Public License as published by the
14 Free Software Foundation; either version 2, or (at your option) any
15 later version.
16
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.
21
22 You should have received a copy of the GNU General Public License
23 along with this program; if not, write to the Free Software
24 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
25 USA. */
26
27
28/* This tells Alpha OSF/1 not to define a getopt prototype in <stdio.h>.
29 Ditto for AIX 3.2 and <stdlib.h>. */
30#ifndef _NO_PROTO
31# define _NO_PROTO
32#endif
33
34#ifdef HAVE_CONFIG_H
35# include <config.h>
36#endif
37
38#if !defined __STDC__ || !__STDC__
39/* This is a separate conditional since some stdc systems
40 reject `defined (const)'. */
41# ifndef const
42# define const
43# endif
44#endif
45
46#include <stdio.h>
47
48/* Comment out all this code if we are using the GNU C Library, and are not
49 actually compiling the library itself. This code is part of the GNU C
50 Library, but also included in many other GNU distributions. Compiling
51 and linking in this code is a waste when using the GNU C library
52 (especially if it is a shared library). Rather than having every GNU
53 program understand `configure --with-gnu-libc' and omit the object files,
54 it is simpler to just do this in the source for each such file. */
55
56#define GETOPT_INTERFACE_VERSION 2
57#if !defined _LIBC && defined __GLIBC__ && __GLIBC__ >= 2
58# include <gnu-versions.h>
59# if _GNU_GETOPT_INTERFACE_VERSION == GETOPT_INTERFACE_VERSION
60# define ELIDE_CODE
61# endif
62#endif
63
64#ifndef ELIDE_CODE
65
66
67/* This needs to come after some library #include
68 to get __GNU_LIBRARY__ defined. */
69#ifdef __GNU_LIBRARY__
70/* Don't include stdlib.h for non-GNU C libraries because some of them
71 contain conflicting prototypes for getopt. */
72# include <stdlib.h>
73# include <unistd.h>
74#endif /* GNU C library. */
75
76#ifdef VMS
77# include <unixlib.h>
78# if HAVE_STRING_H - 0
79# include <string.h>
80# endif
81#endif
82
83#ifndef _
84/* This is for other GNU distributions with internationalized messages.
85 When compiling libc, the _ macro is predefined. */
86# ifdef HAVE_LIBINTL_H
87# include <libintl.h>
88# define _(msgid) gettext (msgid)
89# else
90# define _(msgid) (msgid)
91# endif
92#endif
93
94/* This version of `getopt' appears to the caller like standard Unix `getopt'
95 but it behaves differently for the user, since it allows the user
96 to intersperse the options with the other arguments.
97
98 As `getopt' works, it permutes the elements of ARGV so that,
99 when it is done, all the options precede everything else. Thus
100 all application programs are extended to handle flexible argument order.
101
102 Setting the environment variable POSIXLY_CORRECT disables permutation.
103 Then the behavior is completely standard.
104
105 GNU application programs can use a third alternative mode in which
106 they can distinguish the relative order of options and other arguments. */
107
108#include "getopt.h"
109
110/* For communication from `getopt' to the caller.
111 When `getopt' finds an option that takes an argument,
112 the argument value is returned here.
113 Also, when `ordering' is RETURN_IN_ORDER,
114 each non-option ARGV-element is returned here. */
115
116char *optarg = NULL;
117
118/* Index in ARGV of the next element to be scanned.
119 This is used for communication to and from the caller
120 and for communication between successive calls to `getopt'.
121
122 On entry to `getopt', zero means this is the first call; initialize.
123
124 When `getopt' returns -1, this is the index of the first of the
125 non-option elements that the caller should itself scan.
126
127 Otherwise, `optind' communicates from one call to the next
128 how much of ARGV has been scanned so far. */
129
130/* 1003.2 says this must be 1 before any call. */
131int optind = 1;
132
133/* Formerly, initialization of getopt depended on optind==0, which
134 causes problems with re-calling getopt as programs generally don't
135 know that. */
136
137int __getopt_initialized = 0;
138
139/* The next char to be scanned in the option-element
140 in which the last option character we returned was found.
141 This allows us to pick up the scan where we left off.
142
143 If this is zero, or a null string, it means resume the scan
144 by advancing to the next ARGV-element. */
145
146static char *nextchar;
147
148/* Callers store zero here to inhibit the error message
149 for unrecognized options. */
150
151int opterr = 1;
152
153/* Set to an option character which was unrecognized.
154 This must be initialized on some systems to avoid linking in the
155 system's own getopt implementation. */
156
157int optopt = '?';
158
159/* Describe how to deal with options that follow non-option ARGV-elements.
160
161 If the caller did not specify anything,
162 the default is REQUIRE_ORDER if the environment variable
163 POSIXLY_CORRECT is defined, PERMUTE otherwise.
164
165 REQUIRE_ORDER means don't recognize them as options;
166 stop option processing when the first non-option is seen.
167 This is what Unix does.
168 This mode of operation is selected by either setting the environment
169 variable POSIXLY_CORRECT, or using `+' as the first character
170 of the list of option characters.
171
172 PERMUTE is the default. We permute the contents of ARGV as we scan,
173 so that eventually all the non-options are at the end. This allows options
174 to be given in any order, even with programs that were not written to
175 expect this.
176
177 RETURN_IN_ORDER is an option available to programs that were written
178 to expect options and other ARGV-elements in any order and that care about
179 the ordering of the two. We describe each non-option ARGV-element
180 as if it were the argument of an option with character code 1.
181 Using `-' as the first character of the list of option characters
182 selects this mode of operation.
183
184 The special argument `--' forces an end of option-scanning regardless
185 of the value of `ordering'. In the case of RETURN_IN_ORDER, only
186 `--' can cause `getopt' to return -1 with `optind' != ARGC. */
187
188static enum
189{
190 REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER
191} ordering;
192
193/* Value of POSIXLY_CORRECT environment variable. */
194static char *posixly_correct;
195
196
197#ifdef __GNU_LIBRARY__
198/* We want to avoid inclusion of string.h with non-GNU libraries
199 because there are many ways it can cause trouble.
200 On some systems, it contains special magic macros that don't work
201 in GCC. */
202# include <string.h>
203# define my_index strchr
204#elif defined(_MSC_VER)
205
206# include <stdlib.h>
207# include <string.h>
208# include <stdio.h>
209# define my_index strchr
210#else
211
212/* Avoid depending on library functions or files
213 whose names are inconsistent. */
214
215#ifndef getenv
216extern char *getenv ();
217#endif
218#ifndef strncmp
219extern int strncmp ();
220#endif
221
222static char *
223my_index (str, chr)
224 const char *str;
225 int chr;
226{
227 while (*str)
228 {
229 if (*str == chr)
230 return (char *) str;
231 str++;
232 }
233 return 0;
234}
235
236/* If using GCC, we can safely declare strlen this way.
237 If not using GCC, it is ok not to declare it. */
238#ifdef __GNUC__
239/* Note that Motorola Delta 68k R3V7 comes with GCC but not stddef.h.
240 That was relevant to code that was here before. */
241# if (!defined __STDC__ || !__STDC__) && !defined strlen
242/* gcc with -traditional declares the built-in strlen to return int,
243 and has done so at least since version 2.4.5. -- rms. */
244extern int strlen (const char *);
245# endif /* not __STDC__ */
246#endif /* __GNUC__ */
247
248#endif /* not __GNU_LIBRARY__ */
249
250
251/* Handle permutation of arguments. */
252
253/* Describe the part of ARGV that contains non-options that have
254 been skipped. `first_nonopt' is the index in ARGV of the first of them;
255 `last_nonopt' is the index after the last of them. */
256
257static int first_nonopt;
258static int last_nonopt;
259
260#ifdef _LIBC
261/* Bash 2.0 gives us an environment variable containing flags
262 indicating ARGV elements that should not be considered arguments. */
263
264/* Defined in getopt_init.c */
265extern char *__getopt_nonoption_flags;
266
267static int nonoption_flags_max_len;
268static int nonoption_flags_len;
269
270static int original_argc;
271static char *const *original_argv;
272
273/* Make sure the environment variable bash 2.0 puts in the environment
274 is valid for the getopt call we must make sure that the ARGV passed
275 to getopt is that one passed to the process. */
276static void
277__attribute__ ((unused))
278store_args_and_env (int argc, char *const *argv)
279{
280 /* XXX This is no good solution. We should rather copy the args so
281 that we can compare them later. But we must not use malloc(3). */
282 original_argc = argc;
283 original_argv = argv;
284}
285# ifdef text_set_element
286text_set_element (__libc_subinit, store_args_and_env);
287# endif /* text_set_element */
288
289# define SWAP_FLAGS(ch1, ch2) \
290 if (nonoption_flags_len > 0) \
291 { \
292 char __tmp = __getopt_nonoption_flags[ch1]; \
293 __getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2]; \
294 __getopt_nonoption_flags[ch2] = __tmp; \
295 }
296#else /* !_LIBC */
297# define SWAP_FLAGS(ch1, ch2)
298#endif /* _LIBC */
299
300/* Exchange two adjacent subsequences of ARGV.
301 One subsequence is elements [first_nonopt,last_nonopt)
302 which contains all the non-options that have been skipped so far.
303 The other is elements [last_nonopt,optind), which contains all
304 the options processed since those non-options were skipped.
305
306 `first_nonopt' and `last_nonopt' are relocated so that they describe
307 the new indices of the non-options in ARGV after they are moved. */
308
309#if defined __STDC__ && __STDC__
310static void exchange (char **);
311#endif
312
313static void
314exchange (argv)
315 char **argv;
316{
317 int bottom = first_nonopt;
318 int middle = last_nonopt;
319 int top = optind;
320 char *tem;
321
322 /* Exchange the shorter segment with the far end of the longer segment.
323 That puts the shorter segment into the right place.
324 It leaves the longer segment in the right place overall,
325 but it consists of two parts that need to be swapped next. */
326
327#ifdef _LIBC
328 /* First make sure the handling of the `__getopt_nonoption_flags'
329 string can work normally. Our top argument must be in the range
330 of the string. */
331 if (nonoption_flags_len > 0 && top >= nonoption_flags_max_len)
332 {
333 /* We must extend the array. The user plays games with us and
334 presents new arguments. */
335 char *new_str = malloc (top + 1);
336 if (new_str == NULL)
337 nonoption_flags_len = nonoption_flags_max_len = 0;
338 else
339 {
340 memset (__mempcpy (new_str, __getopt_nonoption_flags,
341 nonoption_flags_max_len),
342 '\0', top + 1 - nonoption_flags_max_len);
343 nonoption_flags_max_len = top + 1;
344 __getopt_nonoption_flags = new_str;
345 }
346 }
347#endif
348
349 while (top > middle && middle > bottom)
350 {
351 if (top - middle > middle - bottom)
352 {
353 /* Bottom segment is the short one. */
354 int len = middle - bottom;
355 register int i;
356
357 /* Swap it with the top part of the top segment. */
358 for (i = 0; i < len; i++)
359 {
360 tem = argv[bottom + i];
361 argv[bottom + i] = argv[top - (middle - bottom) + i];
362 argv[top - (middle - bottom) + i] = tem;
363 SWAP_FLAGS (bottom + i, top - (middle - bottom) + i);
364 }
365 /* Exclude the moved bottom segment from further swapping. */
366 top -= len;
367 }
368 else
369 {
370 /* Top segment is the short one. */
371 int len = top - middle;
372 register int i;
373
374 /* Swap it with the bottom part of the bottom segment. */
375 for (i = 0; i < len; i++)
376 {
377 tem = argv[bottom + i];
378 argv[bottom + i] = argv[middle + i];
379 argv[middle + i] = tem;
380 SWAP_FLAGS (bottom + i, middle + i);
381 }
382 /* Exclude the moved top segment from further swapping. */
383 bottom += len;
384 }
385 }
386
387 /* Update records for the slots the non-options now occupy. */
388
389 first_nonopt += (optind - last_nonopt);
390 last_nonopt = optind;
391}
392
393/* Initialize the internal data when the first call is made. */
394
395#if defined __STDC__ && __STDC__
396static const char *_getopt_initialize (int, char *const *, const char *);
397#endif
398static const char *
399_getopt_initialize (argc, argv, optstring)
400 int argc;
401 char *const *argv;
402 const char *optstring;
403{
404 /* Start processing options with ARGV-element 1 (since ARGV-element 0
405 is the program name); the sequence of previously skipped
406 non-option ARGV-elements is empty. */
407
408 first_nonopt = last_nonopt = optind;
409
410 nextchar = NULL;
411
412 posixly_correct = getenv ("POSIXLY_CORRECT");
413
414 /* Determine how to handle the ordering of options and nonoptions. */
415
416 if (optstring[0] == '-')
417 {
418 ordering = RETURN_IN_ORDER;
419 ++optstring;
420 }
421 else if (optstring[0] == '+')
422 {
423 ordering = REQUIRE_ORDER;
424 ++optstring;
425 }
426 else if (posixly_correct != NULL)
427 ordering = REQUIRE_ORDER;
428 else
429 ordering = PERMUTE;
430
431#ifdef _LIBC
432 if (posixly_correct == NULL
433 && argc == original_argc && argv == original_argv)
434 {
435 if (nonoption_flags_max_len == 0)
436 {
437 if (__getopt_nonoption_flags == NULL
438 || __getopt_nonoption_flags[0] == '\0')
439 nonoption_flags_max_len = -1;
440 else
441 {
442 const char *orig_str = __getopt_nonoption_flags;
443 int len = nonoption_flags_max_len = strlen (orig_str);
444 if (nonoption_flags_max_len < argc)
445 nonoption_flags_max_len = argc;
446 __getopt_nonoption_flags =
447 (char *) malloc (nonoption_flags_max_len);
448 if (__getopt_nonoption_flags == NULL)
449 nonoption_flags_max_len = -1;
450 else
451 memset (__mempcpy (__getopt_nonoption_flags, orig_str, len),
452 '\0', nonoption_flags_max_len - len);
453 }
454 }
455 nonoption_flags_len = nonoption_flags_max_len;
456 }
457 else
458 nonoption_flags_len = 0;
459#endif
460
461 return optstring;
462}
463
464
465/* Scan elements of ARGV (whose length is ARGC) for option characters
466 given in OPTSTRING.
467
468 If an element of ARGV starts with '-', and is not exactly "-" or "--",
469 then it is an option element. The characters of this element
470 (aside from the initial '-') are option characters. If `getopt'
471 is called repeatedly, it returns successively each of the option characters
472 from each of the option elements.
473
474 If `getopt' finds another option character, it returns that character,
475 updating `optind' and `nextchar' so that the next call to `getopt' can
476 resume the scan with the following option character or ARGV-element.
477
478 If there are no more option characters, `getopt' returns -1.
479 Then `optind' is the index in ARGV of the first ARGV-element
480 that is not an option. (The ARGV-elements have been permuted
481 so that those that are not options now come last.)
482
483 OPTSTRING is a string containing the legitimate option characters.
484 If an option character is seen that is not listed in OPTSTRING,
485 return '?' after printing an error message. If you set `opterr' to
486 zero, the error message is suppressed but we still return '?'.
487
488 If a char in OPTSTRING is followed by a colon, that means it wants an arg,
489 so the following text in the same ARGV-element, or the text of the following
490 ARGV-element, is returned in `optarg'. Two colons mean an option that
491 wants an optional arg; if there is text in the current ARGV-element,
492 it is returned in `optarg', otherwise `optarg' is set to zero.
493
494 If OPTSTRING starts with `-' or `+', it requests different methods of
495 handling the non-option ARGV-elements.
496 See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
497
498 Long-named options begin with `--' instead of `-'.
499 Their names may be abbreviated as long as the abbreviation is unique
500 or is an exact match for some defined option. If they have an
501 argument, it follows the option name in the same ARGV-element, separated
502 from the option name by a `=', or else the in next ARGV-element.
503 When `getopt' finds a long-named option, it returns 0 if that option's
504 `flag' field is nonzero, the value of the option's `val' field
505 if the `flag' field is zero.
506
507 The elements of ARGV aren't really const, because we permute them.
508 But we pretend they're const in the prototype to be compatible
509 with other systems.
510
511 LONGOPTS is a vector of `struct option' terminated by an
512 element containing a name which is zero.
513
514 LONGIND returns the index in LONGOPT of the long-named option found.
515 It is only valid when a long-named option has been found by the most
516 recent call.
517
518 If LONG_ONLY is nonzero, '-' as well as '--' can introduce
519 long-named options. */
520
521int
522_getopt_internal (argc, argv, optstring, longopts, longind, long_only)
523 int argc;
524 char *const *argv;
525 const char *optstring;
526 const struct option *longopts;
527 int *longind;
528 int long_only;
529{
530 optarg = NULL;
531
532 if (optind == 0 || !__getopt_initialized)
533 {
534 if (optind == 0)
535 optind = 1; /* Don't scan ARGV[0], the program name. */
536 optstring = _getopt_initialize (argc, argv, optstring);
537 __getopt_initialized = 1;
538 }
539
540 /* Test whether ARGV[optind] points to a non-option argument.
541 Either it does not have option syntax, or there is an environment flag
542 from the shell indicating it is not an option. The later information
543 is only used when the used in the GNU libc. */
544#ifdef _LIBC
545# define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0' \
546 || (optind < nonoption_flags_len \
547 && __getopt_nonoption_flags[optind] == '1'))
548#else
549# define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0')
550#endif
551
552 if (nextchar == NULL || *nextchar == '\0')
553 {
554 /* Advance to the next ARGV-element. */
555
556 /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
557 moved back by the user (who may also have changed the arguments). */
558 if (last_nonopt > optind)
559 last_nonopt = optind;
560 if (first_nonopt > optind)
561 first_nonopt = optind;
562
563 if (ordering == PERMUTE)
564 {
565 /* If we have just processed some options following some non-options,
566 exchange them so that the options come first. */
567
568 if (first_nonopt != last_nonopt && last_nonopt != optind)
569 exchange ((char **) argv);
570 else if (last_nonopt != optind)
571 first_nonopt = optind;
572
573 /* Skip any additional non-options
574 and extend the range of non-options previously skipped. */
575
576 while (optind < argc && NONOPTION_P)
577 optind++;
578 last_nonopt = optind;
579 }
580
581 /* The special ARGV-element `--' means premature end of options.
582 Skip it like a null option,
583 then exchange with previous non-options as if it were an option,
584 then skip everything else like a non-option. */
585
586 if (optind != argc && !strcmp (argv[optind], "--"))
587 {
588 optind++;
589
590 if (first_nonopt != last_nonopt && last_nonopt != optind)
591 exchange ((char **) argv);
592 else if (first_nonopt == last_nonopt)
593 first_nonopt = optind;
594 last_nonopt = argc;
595
596 optind = argc;
597 }
598
599 /* If we have done all the ARGV-elements, stop the scan
600 and back over any non-options that we skipped and permuted. */
601
602 if (optind == argc)
603 {
604 /* Set the next-arg-index to point at the non-options
605 that we previously skipped, so the caller will digest them. */
606 if (first_nonopt != last_nonopt)
607 optind = first_nonopt;
608 return -1;
609 }
610
611 /* If we have come to a non-option and did not permute it,
612 either stop the scan or describe it to the caller and pass it by. */
613
614 if (NONOPTION_P)
615 {
616 if (ordering == REQUIRE_ORDER)
617 return -1;
618 optarg = argv[optind++];
619 return 1;
620 }
621
622 /* We have found another option-ARGV-element.
623 Skip the initial punctuation. */
624
625 nextchar = (argv[optind] + 1
626 + (longopts != NULL && argv[optind][1] == '-'));
627 }
628
629 /* Decode the current option-ARGV-element. */
630
631 /* Check whether the ARGV-element is a long option.
632
633 If long_only and the ARGV-element has the form "-f", where f is
634 a valid short option, don't consider it an abbreviated form of
635 a long option that starts with f. Otherwise there would be no
636 way to give the -f short option.
637
638 On the other hand, if there's a long option "fubar" and
639 the ARGV-element is "-fu", do consider that an abbreviation of
640 the long option, just like "--fu", and not "-f" with arg "u".
641
642 This distinction seems to be the most useful approach. */
643
644 if (longopts != NULL
645 && (argv[optind][1] == '-'
646 || (long_only && (argv[optind][2] || !my_index (optstring, argv[optind][1])))))
647 {
648 char *nameend;
649 const struct option *p;
650 const struct option *pfound = NULL;
651 int exact = 0;
652 int ambig = 0;
653 int indfound = -1;
654 int option_index;
655
656 for (nameend = nextchar; *nameend && *nameend != '='; nameend++)
657 /* Do nothing. */ ;
658
659 /* Test all long options for either exact match
660 or abbreviated matches. */
661 for (p = longopts, option_index = 0; p->name; p++, option_index++)
662 if (!strncmp (p->name, nextchar, nameend - nextchar))
663 {
664 if ((unsigned int) (nameend - nextchar)
665 == (unsigned int) strlen (p->name))
666 {
667 /* Exact match found. */
668 pfound = p;
669 indfound = option_index;
670 exact = 1;
671 break;
672 }
673 else if (pfound == NULL)
674 {
675 /* First nonexact match found. */
676 pfound = p;
677 indfound = option_index;
678 }
679 else
680 /* Second or later nonexact match found. */
681 ambig = 1;
682 }
683
684 if (ambig && !exact)
685 {
686 if (opterr)
687 fprintf (stderr, _("%s: option `%s' is ambiguous\n"),
688 argv[0], argv[optind]);
689 nextchar += strlen (nextchar);
690 optind++;
691 optopt = 0;
692 return '?';
693 }
694
695 if (pfound != NULL)
696 {
697 option_index = indfound;
698 optind++;
699 if (*nameend)
700 {
701 /* Don't test has_arg with >, because some C compilers don't
702 allow it to be used on enums. */
703 if (pfound->has_arg)
704 optarg = nameend + 1;
705 else
706 {
707 if (opterr)
708 if (argv[optind - 1][1] == '-')
709 /* --option */
710 fprintf (stderr,
711 _("%s: option `--%s' doesn't allow an argument\n"),
712 argv[0], pfound->name);
713 else
714 /* +option or -option */
715 fprintf (stderr,
716 _("%s: option `%c%s' doesn't allow an argument\n"),
717 argv[0], argv[optind - 1][0], pfound->name);
718
719 nextchar += strlen (nextchar);
720
721 optopt = pfound->val;
722 return '?';
723 }
724 }
725 else if (pfound->has_arg == 1)
726 {
727 if (optind < argc)
728 optarg = argv[optind++];
729 else
730 {
731 if (opterr)
732 fprintf (stderr,
733 _("%s: option `%s' requires an argument\n"),
734 argv[0], argv[optind - 1]);
735 nextchar += strlen (nextchar);
736 optopt = pfound->val;
737 return optstring[0] == ':' ? ':' : '?';
738 }
739 }
740 nextchar += strlen (nextchar);
741 if (longind != NULL)
742 *longind = option_index;
743 if (pfound->flag)
744 {
745 *(pfound->flag) = pfound->val;
746 return 0;
747 }
748 return pfound->val;
749 }
750
751 /* Can't find it as a long option. If this is not getopt_long_only,
752 or the option starts with '--' or is not a valid short
753 option, then it's an error.
754 Otherwise interpret it as a short option. */
755 if (!long_only || argv[optind][1] == '-'
756 || my_index (optstring, *nextchar) == NULL)
757 {
758 if (opterr)
759 {
760 if (argv[optind][1] == '-')
761 /* --option */
762 fprintf (stderr, _("%s: unrecognized option `--%s'\n"),
763 argv[0], nextchar);
764 else
765 /* +option or -option */
766 fprintf (stderr, _("%s: unrecognized option `%c%s'\n"),
767 argv[0], argv[optind][0], nextchar);
768 }
769 nextchar = (char *) "";
770 optind++;
771 optopt = 0;
772 return '?';
773 }
774 }
775
776 /* Look at and handle the next short option-character. */
777
778 {
779 char c = *nextchar++;
780 char *temp = my_index (optstring, c);
781
782 /* Increment `optind' when we start to process its last character. */
783 if (*nextchar == '\0')
784 ++optind;
785
786 if (temp == NULL || c == ':')
787 {
788 if (opterr)
789 {
790 if (posixly_correct)
791 /* 1003.2 specifies the format of this message. */
792 fprintf (stderr, _("%s: illegal option -- %c\n"),
793 argv[0], c);
794 else
795 fprintf (stderr, _("%s: invalid option -- %c\n"),
796 argv[0], c);
797 }
798 optopt = c;
799 return '?';
800 }
801 /* Convenience. Treat POSIX -W foo same as long option --foo */
802 if (temp[0] == 'W' && temp[1] == ';')
803 {
804 char *nameend;
805 const struct option *p;
806 const struct option *pfound = NULL;
807 int exact = 0;
808 int ambig = 0;
809 int indfound = 0;
810 int option_index;
811
812 /* This is an option that requires an argument. */
813 if (*nextchar != '\0')
814 {
815 optarg = nextchar;
816 /* If we end this ARGV-element by taking the rest as an arg,
817 we must advance to the next element now. */
818 optind++;
819 }
820 else if (optind == argc)
821 {
822 if (opterr)
823 {
824 /* 1003.2 specifies the format of this message. */
825 fprintf (stderr, _("%s: option requires an argument -- %c\n"),
826 argv[0], c);
827 }
828 optopt = c;
829 if (optstring[0] == ':')
830 c = ':';
831 else
832 c = '?';
833 return c;
834 }
835 else
836 /* We already incremented `optind' once;
837 increment it again when taking next ARGV-elt as argument. */
838 optarg = argv[optind++];
839
840 /* optarg is now the argument, see if it's in the
841 table of longopts. */
842
843 for (nextchar = nameend = optarg; *nameend && *nameend != '='; nameend++)
844 /* Do nothing. */ ;
845
846 /* Test all long options for either exact match
847 or abbreviated matches. */
848 for (p = longopts, option_index = 0; p->name; p++, option_index++)
849 if (!strncmp (p->name, nextchar, nameend - nextchar))
850 {
851 if ((unsigned int) (nameend - nextchar) == strlen (p->name))
852 {
853 /* Exact match found. */
854 pfound = p;
855 indfound = option_index;
856 exact = 1;
857 break;
858 }
859 else if (pfound == NULL)
860 {
861 /* First nonexact match found. */
862 pfound = p;
863 indfound = option_index;
864 }
865 else
866 /* Second or later nonexact match found. */
867 ambig = 1;
868 }
869 if (ambig && !exact)
870 {
871 if (opterr)
872 fprintf (stderr, _("%s: option `-W %s' is ambiguous\n"),
873 argv[0], argv[optind]);
874 nextchar += strlen (nextchar);
875 optind++;
876 return '?';
877 }
878 if (pfound != NULL)
879 {
880 option_index = indfound;
881 if (*nameend)
882 {
883 /* Don't test has_arg with >, because some C compilers don't
884 allow it to be used on enums. */
885 if (pfound->has_arg)
886 optarg = nameend + 1;
887 else
888 {
889 if (opterr)
890 fprintf (stderr, _("\
891%s: option `-W %s' doesn't allow an argument\n"),
892 argv[0], pfound->name);
893
894 nextchar += strlen (nextchar);
895 return '?';
896 }
897 }
898 else if (pfound->has_arg == 1)
899 {
900 if (optind < argc)
901 optarg = argv[optind++];
902 else
903 {
904 if (opterr)
905 fprintf (stderr,
906 _("%s: option `%s' requires an argument\n"),
907 argv[0], argv[optind - 1]);
908 nextchar += strlen (nextchar);
909 return optstring[0] == ':' ? ':' : '?';
910 }
911 }
912 nextchar += strlen (nextchar);
913 if (longind != NULL)
914 *longind = option_index;
915 if (pfound->flag)
916 {
917 *(pfound->flag) = pfound->val;
918 return 0;
919 }
920 return pfound->val;
921 }
922 nextchar = NULL;
923 return 'W'; /* Let the application handle it. */
924 }
925 if (temp[1] == ':')
926 {
927 if (temp[2] == ':')
928 {
929 /* This is an option that accepts an argument optionally. */
930 if (*nextchar != '\0')
931 {
932 optarg = nextchar;
933 optind++;
934 }
935 else
936 optarg = NULL;
937 nextchar = NULL;
938 }
939 else
940 {
941 /* This is an option that requires an argument. */
942 if (*nextchar != '\0')
943 {
944 optarg = nextchar;
945 /* If we end this ARGV-element by taking the rest as an arg,
946 we must advance to the next element now. */
947 optind++;
948 }
949 else if (optind == argc)
950 {
951 if (opterr)
952 {
953 /* 1003.2 specifies the format of this message. */
954 fprintf (stderr,
955 _("%s: option requires an argument -- %c\n"),
956 argv[0], c);
957 }
958 optopt = c;
959 if (optstring[0] == ':')
960 c = ':';
961 else
962 c = '?';
963 }
964 else
965 /* We already incremented `optind' once;
966 increment it again when taking next ARGV-elt as argument. */
967 optarg = argv[optind++];
968 nextchar = NULL;
969 }
970 }
971 return c;
972 }
973}
974
975int
976getopt (argc, argv, optstring)
977 int argc;
978 char *const *argv;
979 const char *optstring;
980{
981 return _getopt_internal (argc, argv, optstring,
982 (const struct option *) 0,
983 (int *) 0,
984 0);
985}
986
987#endif /* Not ELIDE_CODE. */
988
989
990#ifdef TEST
991
992/* Compile with -DTEST to make an executable for use in testing
993 the above definition of `getopt'. */
994
995int
996main (argc, argv)
997 int argc;
998 char **argv;
999{
1000 int c;
1001 int digit_optind = 0;
1002
1003 while (1)
1004 {
1005 int this_option_optind = optind ? optind : 1;
1006
1007 c = getopt (argc, argv, "abc:d:0123456789");
1008 if (c == -1)
1009 break;
1010
1011 switch (c)
1012 {
1013 case '0':
1014 case '1':
1015 case '2':
1016 case '3':
1017 case '4':
1018 case '5':
1019 case '6':
1020 case '7':
1021 case '8':
1022 case '9':
1023 if (digit_optind != 0 && digit_optind != this_option_optind)
1024 printf ("digits occur in two different argv-elements.\n");
1025 digit_optind = this_option_optind;
1026 printf ("option %c\n", c);
1027 break;
1028
1029 case 'a':
1030 printf ("option a\n");
1031 break;
1032
1033 case 'b':
1034 printf ("option b\n");
1035 break;
1036
1037 case 'c':
1038 printf ("option c with value `%s'\n", optarg);
1039 break;
1040
1041 case '?':
1042 break;
1043
1044 default:
1045 printf ("?? getopt returned character code 0%o ??\n", c);
1046 }
1047 }
1048
1049 if (optind < argc)
1050 {
1051 printf ("non-option ARGV-elements: ");
1052 while (optind < argc)
1053 printf ("%s ", argv[optind++]);
1054 printf ("\n");
1055 }
1056
1057 exit (0);
1058}
1059
1060#endif /* TEST */
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette