Code

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