getopt.c
Go to the documentation of this file.
00001 /* Getopt for GNU.
00002    NOTE: getopt is now part of the C library, so if you don't know what
00003    "Keep this file name-space clean" means, talk to drepper@gnu.org
00004    before changing it!
00005 
00006    Copyright (C) 1987, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 2000
00007         Free Software Foundation, Inc.
00008 
00009    The GNU C Library is free software; you can redistribute it and/or
00010    modify it under the terms of the GNU Library General Public License as
00011    published by the Free Software Foundation; either version 2 of the
00012    License, or (at your option) any later version.
00013 
00014    The GNU C Library is distributed in the hope that it will be useful,
00015    but WITHOUT ANY WARRANTY; without even the implied warranty of
00016    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00017    Library General Public License for more details.
00018 
00019    You should have received a copy of the GNU Library General Public
00020    License along with the GNU C Library; see the file COPYING.LIB.  If not,
00021    write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
00022    Boston, MA 02111-1307, USA.  */
00023 
00024 /* This tells Alpha OSF/1 not to define a getopt prototype in <stdio.h>.
00025    Ditto for AIX 3.2 and <stdlib.h>.  */
00026 #ifndef _NO_PROTO
00027 # define _NO_PROTO
00028 #endif
00029 
00030 #ifdef HAVE_CONFIG_H
00031 # include <config.h>
00032 #endif
00033 
00034 #if !defined __STDC__ || !__STDC__
00035 /* This is a separate conditional since some stdc systems
00036    reject `defined (const)'.  */
00037 # ifndef const
00038 #  define const
00039 # endif
00040 #endif
00041 
00042 #include <stdio.h>
00043 
00044 /* Comment out all this code if we are using the GNU C Library, and are not
00045    actually compiling the library itself.  This code is part of the GNU C
00046    Library, but also included in many other GNU distributions.  Compiling
00047    and linking in this code is a waste when using the GNU C library
00048    (especially if it is a shared library).  Rather than having every GNU
00049    program understand `configure --with-gnu-libc' and omit the object files,
00050    it is simpler to just do this in the source for each such file.  */
00051 
00052 #define GETOPT_INTERFACE_VERSION 2
00053 #if !defined _LIBC && defined __GLIBC__ && __GLIBC__ >= 2
00054 # include <gnu-versions.h>
00055 # if _GNU_GETOPT_INTERFACE_VERSION == GETOPT_INTERFACE_VERSION
00056 #  define ELIDE_CODE
00057 # endif
00058 #endif
00059 
00060 #ifndef ELIDE_CODE
00061 
00062 
00063 /* This needs to come after some library #include
00064    to get __GNU_LIBRARY__ defined.  */
00065 #ifdef  __GNU_LIBRARY__
00066 /* Don't include stdlib.h for non-GNU C libraries because some of them
00067    contain conflicting prototypes for getopt.  */
00068 # include <stdlib.h>
00069 # include <unistd.h>
00070 #endif  /* GNU C library.  */
00071 
00072 #ifdef VMS
00073 # include <unixlib.h>
00074 # if HAVE_STRING_H - 0
00075 #  include <string.h>
00076 # endif
00077 #endif
00078 
00079 #ifndef _
00080 /* This is for other GNU distributions with internationalized messages.  */
00081 # if defined HAVE_LIBINTL_H || defined _LIBC
00082 #  include <libintl.h>
00083 #  ifndef _
00084 #   define _(msgid)     gettext (msgid)
00085 #  endif
00086 # else
00087 #  define _(msgid)      (msgid)
00088 # endif
00089 #endif
00090 
00091 /* This version of `getopt' appears to the caller like standard Unix `getopt'
00092    but it behaves differently for the user, since it allows the user
00093    to intersperse the options with the other arguments.
00094 
00095    As `getopt' works, it permutes the elements of ARGV so that,
00096    when it is done, all the options precede everything else.  Thus
00097    all application programs are extended to handle flexible argument order.
00098 
00099    Setting the environment variable POSIXLY_CORRECT disables permutation.
00100    Then the behavior is completely standard.
00101 
00102    GNU application programs can use a third alternative mode in which
00103    they can distinguish the relative order of options and other arguments.  */
00104 
00105 #include "getopt.h"
00106 
00107 /* For communication from `getopt' to the caller.
00108    When `getopt' finds an option that takes an argument,
00109    the argument value is returned here.
00110    Also, when `ordering' is RETURN_IN_ORDER,
00111    each non-option ARGV-element is returned here.  */
00112 
00113 char *optarg;
00114 
00115 /* Index in ARGV of the next element to be scanned.
00116    This is used for communication to and from the caller
00117    and for communication between successive calls to `getopt'.
00118 
00119    On entry to `getopt', zero means this is the first call; initialize.
00120 
00121    When `getopt' returns -1, this is the index of the first of the
00122    non-option elements that the caller should itself scan.
00123 
00124    Otherwise, `optind' communicates from one call to the next
00125    how much of ARGV has been scanned so far.  */
00126 
00127 /* 1003.2 says this must be 1 before any call.  */
00128 int optind = 1;
00129 
00130 /* Formerly, initialization of getopt depended on optind==0, which
00131    causes problems with re-calling getopt as programs generally don't
00132    know that. */
00133 
00134 int __getopt_initialized;
00135 
00136 /* The next char to be scanned in the option-element
00137    in which the last option character we returned was found.
00138    This allows us to pick up the scan where we left off.
00139 
00140    If this is zero, or a null string, it means resume the scan
00141    by advancing to the next ARGV-element.  */
00142 
00143 static char *nextchar;
00144 
00145 /* Callers store zero here to inhibit the error message
00146    for unrecognized options.  */
00147 
00148 int opterr = 1;
00149 
00150 /* Set to an option character which was unrecognized.
00151    This must be initialized on some systems to avoid linking in the
00152    system's own getopt implementation.  */
00153 
00154 int optopt = '?';
00155 
00156 /* Describe how to deal with options that follow non-option ARGV-elements.
00157 
00158    If the caller did not specify anything,
00159    the default is REQUIRE_ORDER if the environment variable
00160    POSIXLY_CORRECT is defined, PERMUTE otherwise.
00161 
00162    REQUIRE_ORDER means don't recognize them as options;
00163    stop option processing when the first non-option is seen.
00164    This is what Unix does.
00165    This mode of operation is selected by either setting the environment
00166    variable POSIXLY_CORRECT, or using `+' as the first character
00167    of the list of option characters.
00168 
00169    PERMUTE is the default.  We permute the contents of ARGV as we scan,
00170    so that eventually all the non-options are at the end.  This allows options
00171    to be given in any order, even with programs that were not written to
00172    expect this.
00173 
00174    RETURN_IN_ORDER is an option available to programs that were written
00175    to expect options and other ARGV-elements in any order and that care about
00176    the ordering of the two.  We describe each non-option ARGV-element
00177    as if it were the argument of an option with character code 1.
00178    Using `-' as the first character of the list of option characters
00179    selects this mode of operation.
00180 
00181    The special argument `--' forces an end of option-scanning regardless
00182    of the value of `ordering'.  In the case of RETURN_IN_ORDER, only
00183    `--' can cause `getopt' to return -1 with `optind' != ARGC.  */
00184 
00185 static enum
00186 {
00187   REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER
00188 } ordering;
00189 
00190 /* Value of POSIXLY_CORRECT environment variable.  */
00191 static char *posixly_correct;
00192 
00193 #ifdef  __GNU_LIBRARY__
00194 /* We want to avoid inclusion of string.h with non-GNU libraries
00195    because there are many ways it can cause trouble.
00196    On some systems, it contains special magic macros that don't work
00197    in GCC.  */
00198 # include <string.h>
00199 # define my_index       strchr
00200 #else
00201 
00202 # if HAVE_STRING_H
00203 #  include <string.h>
00204 # else
00205 #  include <strings.h>
00206 # endif
00207 
00208 /* Avoid depending on library functions or files
00209    whose names are inconsistent.  */
00210 
00211 #ifndef getenv
00212 extern char *getenv ();
00213 #endif
00214 
00215 static char *
00216 my_index (str, chr)
00217      const char *str;
00218      int chr;
00219 {
00220   while (*str)
00221     {
00222       if (*str == chr)
00223         return (char *) str;
00224       str++;
00225     }
00226   return 0;
00227 }
00228 
00229 /* If using GCC, we can safely declare strlen this way.
00230    If not using GCC, it is ok not to declare it.  */
00231 #ifdef __GNUC__
00232 /* Note that Motorola Delta 68k R3V7 comes with GCC but not stddef.h.
00233    That was relevant to code that was here before.  */
00234 # if (!defined __STDC__ || !__STDC__) && !defined strlen
00235 /* gcc with -traditional declares the built-in strlen to return int,
00236    and has done so at least since version 2.4.5. -- rms.  */
00237 extern int strlen (const char *);
00238 # endif /* not __STDC__ */
00239 #endif /* __GNUC__ */
00240 
00241 #endif /* not __GNU_LIBRARY__ */
00242 
00243 /* Handle permutation of arguments.  */
00244 
00245 /* Describe the part of ARGV that contains non-options that have
00246    been skipped.  `first_nonopt' is the index in ARGV of the first of them;
00247    `last_nonopt' is the index after the last of them.  */
00248 
00249 static int first_nonopt;
00250 static int last_nonopt;
00251 
00252 #ifdef _LIBC
00253 /* Bash 2.0 gives us an environment variable containing flags
00254    indicating ARGV elements that should not be considered arguments.  */
00255 
00256 /* Defined in getopt_init.c  */
00257 extern char *__getopt_nonoption_flags;
00258 
00259 static int nonoption_flags_max_len;
00260 static int nonoption_flags_len;
00261 
00262 static int original_argc;
00263 static char *const *original_argv;
00264 
00265 /* Make sure the environment variable bash 2.0 puts in the environment
00266    is valid for the getopt call we must make sure that the ARGV passed
00267    to getopt is that one passed to the process.  */
00268 static void
00269 __attribute__ ((unused))
00270 store_args_and_env (int argc, char *const *argv)
00271 {
00272   /* XXX This is no good solution.  We should rather copy the args so
00273      that we can compare them later.  But we must not use malloc(3).  */
00274   original_argc = argc;
00275   original_argv = argv;
00276 }
00277 # ifdef text_set_element
00278 text_set_element (__libc_subinit, store_args_and_env);
00279 # endif /* text_set_element */
00280 
00281 # define SWAP_FLAGS(ch1, ch2) \
00282   if (nonoption_flags_len > 0)                                                \
00283     {                                                                         \
00284       char __tmp = __getopt_nonoption_flags[ch1];                             \
00285       __getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2];          \
00286       __getopt_nonoption_flags[ch2] = __tmp;                                  \
00287     }
00288 #else   /* !_LIBC */
00289 # define SWAP_FLAGS(ch1, ch2)
00290 #endif  /* _LIBC */
00291 
00292 /* Exchange two adjacent subsequences of ARGV.
00293    One subsequence is elements [first_nonopt,last_nonopt)
00294    which contains all the non-options that have been skipped so far.
00295    The other is elements [last_nonopt,optind), which contains all
00296    the options processed since those non-options were skipped.
00297 
00298    `first_nonopt' and `last_nonopt' are relocated so that they describe
00299    the new indices of the non-options in ARGV after they are moved.  */
00300 
00301 #if defined __STDC__ && __STDC__
00302 static void exchange (char **);
00303 #endif
00304 
00305 static void
00306 exchange (argv)
00307      char **argv;
00308 {
00309   int bottom = first_nonopt;
00310   int middle = last_nonopt;
00311   int top = optind;
00312   char *tem;
00313 
00314   /* Exchange the shorter segment with the far end of the longer segment.
00315      That puts the shorter segment into the right place.
00316      It leaves the longer segment in the right place overall,
00317      but it consists of two parts that need to be swapped next.  */
00318 
00319 #ifdef _LIBC
00320   /* First make sure the handling of the `__getopt_nonoption_flags'
00321      string can work normally.  Our top argument must be in the range
00322      of the string.  */
00323   if (nonoption_flags_len > 0 && top >= nonoption_flags_max_len)
00324     {
00325       /* We must extend the array.  The user plays games with us and
00326          presents new arguments.  */
00327       char *new_str = malloc (top + 1);
00328       if (new_str == NULL)
00329         nonoption_flags_len = nonoption_flags_max_len = 0;
00330       else
00331         {
00332           memset (__mempcpy (new_str, __getopt_nonoption_flags,
00333                              nonoption_flags_max_len),
00334                   '\0', top + 1 - nonoption_flags_max_len);
00335           nonoption_flags_max_len = top + 1;
00336           __getopt_nonoption_flags = new_str;
00337         }
00338     }
00339 #endif
00340 
00341   while (top > middle && middle > bottom)
00342     {
00343       if (top - middle > middle - bottom)
00344         {
00345           /* Bottom segment is the short one.  */
00346           int len = middle - bottom;
00347           register int i;
00348 
00349           /* Swap it with the top part of the top segment.  */
00350           for (i = 0; i < len; i++)
00351             {
00352               tem = argv[bottom + i];
00353               argv[bottom + i] = argv[top - (middle - bottom) + i];
00354               argv[top - (middle - bottom) + i] = tem;
00355               SWAP_FLAGS (bottom + i, top - (middle - bottom) + i);
00356             }
00357           /* Exclude the moved bottom segment from further swapping.  */
00358           top -= len;
00359         }
00360       else
00361         {
00362           /* Top segment is the short one.  */
00363           int len = top - middle;
00364           register int i;
00365 
00366           /* Swap it with the bottom part of the bottom segment.  */
00367           for (i = 0; i < len; i++)
00368             {
00369               tem = argv[bottom + i];
00370               argv[bottom + i] = argv[middle + i];
00371               argv[middle + i] = tem;
00372               SWAP_FLAGS (bottom + i, middle + i);
00373             }
00374           /* Exclude the moved top segment from further swapping.  */
00375           bottom += len;
00376         }
00377     }
00378 
00379   /* Update records for the slots the non-options now occupy.  */
00380 
00381   first_nonopt += (optind - last_nonopt);
00382   last_nonopt = optind;
00383 }
00384 
00385 /* Initialize the internal data when the first call is made.  */
00386 
00387 #if defined __STDC__ && __STDC__
00388 static const char *_getopt_initialize (int, char *const *, const char *);
00389 #endif
00390 static const char *
00391 _getopt_initialize (argc, argv, optstring)
00392      int argc;
00393      char *const *argv;
00394      const char *optstring;
00395 {
00396   /* Start processing options with ARGV-element 1 (since ARGV-element 0
00397      is the program name); the sequence of previously skipped
00398      non-option ARGV-elements is empty.  */
00399 
00400   first_nonopt = last_nonopt = optind;
00401 
00402   nextchar = NULL;
00403 
00404   posixly_correct = getenv ("POSIXLY_CORRECT");
00405 
00406   /* Determine how to handle the ordering of options and nonoptions.  */
00407 
00408   if (optstring[0] == '-')
00409     {
00410       ordering = RETURN_IN_ORDER;
00411       ++optstring;
00412     }
00413   else if (optstring[0] == '+')
00414     {
00415       ordering = REQUIRE_ORDER;
00416       ++optstring;
00417     }
00418   else if (posixly_correct != NULL)
00419     ordering = REQUIRE_ORDER;
00420   else
00421     ordering = PERMUTE;
00422 
00423 #ifdef _LIBC
00424   if (posixly_correct == NULL
00425       && argc == original_argc && argv == original_argv)
00426     {
00427       if (nonoption_flags_max_len == 0)
00428         {
00429           if (__getopt_nonoption_flags == NULL
00430               || __getopt_nonoption_flags[0] == '\0')
00431             nonoption_flags_max_len = -1;
00432           else
00433             {
00434               const char *orig_str = __getopt_nonoption_flags;
00435               int len = nonoption_flags_max_len = strlen (orig_str);
00436               if (nonoption_flags_max_len < argc)
00437                 nonoption_flags_max_len = argc;
00438               __getopt_nonoption_flags =
00439                 (char *) malloc (nonoption_flags_max_len);
00440               if (__getopt_nonoption_flags == NULL)
00441                 nonoption_flags_max_len = -1;
00442               else
00443                 memset (__mempcpy (__getopt_nonoption_flags, orig_str, len),
00444                         '\0', nonoption_flags_max_len - len);
00445             }
00446         }
00447       nonoption_flags_len = nonoption_flags_max_len;
00448     }
00449   else
00450     nonoption_flags_len = 0;
00451 #endif
00452 
00453   return optstring;
00454 }
00455 
00456 /* Scan elements of ARGV (whose length is ARGC) for option characters
00457    given in OPTSTRING.
00458 
00459    If an element of ARGV starts with '-', and is not exactly "-" or "--",
00460    then it is an option element.  The characters of this element
00461    (aside from the initial '-') are option characters.  If `getopt'
00462    is called repeatedly, it returns successively each of the option characters
00463    from each of the option elements.
00464 
00465    If `getopt' finds another option character, it returns that character,
00466    updating `optind' and `nextchar' so that the next call to `getopt' can
00467    resume the scan with the following option character or ARGV-element.
00468 
00469    If there are no more option characters, `getopt' returns -1.
00470    Then `optind' is the index in ARGV of the first ARGV-element
00471    that is not an option.  (The ARGV-elements have been permuted
00472    so that those that are not options now come last.)
00473 
00474    OPTSTRING is a string containing the legitimate option characters.
00475    If an option character is seen that is not listed in OPTSTRING,
00476    return '?' after printing an error message.  If you set `opterr' to
00477    zero, the error message is suppressed but we still return '?'.
00478 
00479    If a char in OPTSTRING is followed by a colon, that means it wants an arg,
00480    so the following text in the same ARGV-element, or the text of the following
00481    ARGV-element, is returned in `optarg'.  Two colons mean an option that
00482    wants an optional arg; if there is text in the current ARGV-element,
00483    it is returned in `optarg', otherwise `optarg' is set to zero.
00484 
00485    If OPTSTRING starts with `-' or `+', it requests different methods of
00486    handling the non-option ARGV-elements.
00487    See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
00488 
00489    Long-named options begin with `--' instead of `-'.
00490    Their names may be abbreviated as long as the abbreviation is unique
00491    or is an exact match for some defined option.  If they have an
00492    argument, it follows the option name in the same ARGV-element, separated
00493    from the option name by a `=', or else the in next ARGV-element.
00494    When `getopt' finds a long-named option, it returns 0 if that option's
00495    `flag' field is nonzero, the value of the option's `val' field
00496    if the `flag' field is zero.
00497 
00498    The elements of ARGV aren't really const, because we permute them.
00499    But we pretend they're const in the prototype to be compatible
00500    with other systems.
00501 
00502    LONGOPTS is a vector of `struct option' terminated by an
00503    element containing a name which is zero.
00504 
00505    LONGIND returns the index in LONGOPT of the long-named option found.
00506    It is only valid when a long-named option has been found by the most
00507    recent call.
00508 
00509    If LONG_ONLY is nonzero, '-' as well as '--' can introduce
00510    long-named options.  */
00511 
00512 int
00513 _getopt_internal (argc, argv, optstring, longopts, longind, long_only)
00514      int argc;
00515      char *const *argv;
00516      const char *optstring;
00517      const struct option *longopts;
00518      int *longind;
00519      int long_only;
00520 {
00521   int print_errors = opterr;
00522   if (optstring[0] == ':')
00523     print_errors = 0;
00524 
00525   if (argc < 1)
00526     return -1;
00527 
00528   optarg = NULL;
00529 
00530   if (optind == 0 || !__getopt_initialized)
00531     {
00532       if (optind == 0)
00533         optind = 1;     /* Don't scan ARGV[0], the program name.  */
00534       optstring = _getopt_initialize (argc, argv, optstring);
00535       __getopt_initialized = 1;
00536     }
00537 
00538   /* Test whether ARGV[optind] points to a non-option argument.
00539      Either it does not have option syntax, or there is an environment flag
00540      from the shell indicating it is not an option.  The later information
00541      is only used when the used in the GNU libc.  */
00542 #ifdef _LIBC
00543 # define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0'       \
00544                       || (optind < nonoption_flags_len                        \
00545                           && __getopt_nonoption_flags[optind] == '1'))
00546 #else
00547 # define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0')
00548 #endif
00549 
00550   if (nextchar == NULL || *nextchar == '\0')
00551     {
00552       /* Advance to the next ARGV-element.  */
00553 
00554       /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
00555          moved back by the user (who may also have changed the arguments).  */
00556       if (last_nonopt > optind)
00557         last_nonopt = optind;
00558       if (first_nonopt > optind)
00559         first_nonopt = optind;
00560 
00561       if (ordering == PERMUTE)
00562         {
00563           /* If we have just processed some options following some non-options,
00564              exchange them so that the options come first.  */
00565 
00566           if (first_nonopt != last_nonopt && last_nonopt != optind)
00567             exchange ((char **) argv);
00568           else if (last_nonopt != optind)
00569             first_nonopt = optind;
00570 
00571           /* Skip any additional non-options
00572              and extend the range of non-options previously skipped.  */
00573 
00574           while (optind < argc && NONOPTION_P)
00575             optind++;
00576           last_nonopt = optind;
00577         }
00578 
00579       /* The special ARGV-element `--' means premature end of options.
00580          Skip it like a null option,
00581          then exchange with previous non-options as if it were an option,
00582          then skip everything else like a non-option.  */
00583 
00584       if (optind != argc && !strcmp (argv[optind], "--"))
00585         {
00586           optind++;
00587 
00588           if (first_nonopt != last_nonopt && last_nonopt != optind)
00589             exchange ((char **) argv);
00590           else if (first_nonopt == last_nonopt)
00591             first_nonopt = optind;
00592           last_nonopt = argc;
00593 
00594           optind = argc;
00595         }
00596 
00597       /* If we have done all the ARGV-elements, stop the scan
00598          and back over any non-options that we skipped and permuted.  */
00599 
00600       if (optind == argc)
00601         {
00602           /* Set the next-arg-index to point at the non-options
00603              that we previously skipped, so the caller will digest them.  */
00604           if (first_nonopt != last_nonopt)
00605             optind = first_nonopt;
00606           return -1;
00607         }
00608 
00609       /* If we have come to a non-option and did not permute it,
00610          either stop the scan or describe it to the caller and pass it by.  */
00611 
00612       if (NONOPTION_P)
00613         {
00614           if (ordering == REQUIRE_ORDER)
00615             return -1;
00616           optarg = argv[optind++];
00617           return 1;
00618         }
00619 
00620       /* We have found another option-ARGV-element.
00621          Skip the initial punctuation.  */
00622 
00623       nextchar = (argv[optind] + 1
00624                   + (longopts != NULL && argv[optind][1] == '-'));
00625     }
00626 
00627   /* Decode the current option-ARGV-element.  */
00628 
00629   /* Check whether the ARGV-element is a long option.
00630 
00631      If long_only and the ARGV-element has the form "-f", where f is
00632      a valid short option, don't consider it an abbreviated form of
00633      a long option that starts with f.  Otherwise there would be no
00634      way to give the -f short option.
00635 
00636      On the other hand, if there's a long option "fubar" and
00637      the ARGV-element is "-fu", do consider that an abbreviation of
00638      the long option, just like "--fu", and not "-f" with arg "u".
00639 
00640      This distinction seems to be the most useful approach.  */
00641 
00642   if (longopts != NULL
00643       && (argv[optind][1] == '-'
00644           || (long_only && (argv[optind][2] || !my_index (optstring, argv[optind][1])))))
00645     {
00646       char *nameend;
00647       const struct option *p;
00648       const struct option *pfound = NULL;
00649       int exact = 0;
00650       int ambig = 0;
00651       int indfound = -1;
00652       int option_index;
00653 
00654       for (nameend = nextchar; *nameend && *nameend != '='; nameend++)
00655         /* Do nothing.  */ ;
00656 
00657       /* Test all long options for either exact match
00658          or abbreviated matches.  */
00659       for (p = longopts, option_index = 0; p->name; p++, option_index++)
00660         if (!strncmp (p->name, nextchar, nameend - nextchar))
00661           {
00662             if ((unsigned int) (nameend - nextchar)
00663                 == (unsigned int) strlen (p->name))
00664               {
00665                 /* Exact match found.  */
00666                 pfound = p;
00667                 indfound = option_index;
00668                 exact = 1;
00669                 break;
00670               }
00671             else if (pfound == NULL)
00672               {
00673                 /* First nonexact match found.  */
00674                 pfound = p;
00675                 indfound = option_index;
00676               }
00677             else if (long_only
00678                      || pfound->has_arg != p->has_arg
00679                      || pfound->flag != p->flag
00680                      || pfound->val != p->val)
00681               /* Second or later nonexact match found.  */
00682               ambig = 1;
00683           }
00684 
00685       if (ambig && !exact)
00686         {
00687           if (print_errors)
00688             fprintf (stderr, _("%s: option `%s' is ambiguous\n"),
00689                      argv[0], argv[optind]);
00690           nextchar += strlen (nextchar);
00691           optind++;
00692           optopt = 0;
00693           return '?';
00694         }
00695 
00696       if (pfound != NULL)
00697         {
00698           option_index = indfound;
00699           optind++;
00700           if (*nameend)
00701             {
00702               /* Don't test has_arg with >, because some C compilers don't
00703                  allow it to be used on enums.  */
00704               if (pfound->has_arg)
00705                 optarg = nameend + 1;
00706               else
00707                 {
00708                   if (print_errors)
00709                     {
00710                       if (argv[optind - 1][1] == '-')
00711                         /* --option */
00712                         fprintf (stderr,
00713                                  _("%s: option `--%s' doesn't allow an argument\n"),
00714                                  argv[0], pfound->name);
00715                       else
00716                         /* +option or -option */
00717                         fprintf (stderr,
00718                                  _("%s: option `%c%s' doesn't allow an argument\n"),
00719                                  argv[0], argv[optind - 1][0], pfound->name);
00720                     }
00721 
00722                   nextchar += strlen (nextchar);
00723 
00724                   optopt = pfound->val;
00725                   return '?';
00726                 }
00727             }
00728           else if (pfound->has_arg == 1)
00729             {
00730               if (optind < argc)
00731                 optarg = argv[optind++];
00732               else
00733                 {
00734                   if (print_errors)
00735                     fprintf (stderr,
00736                            _("%s: option `%s' requires an argument\n"),
00737                            argv[0], argv[optind - 1]);
00738                   nextchar += strlen (nextchar);
00739                   optopt = pfound->val;
00740                   return optstring[0] == ':' ? ':' : '?';
00741                 }
00742             }
00743           nextchar += strlen (nextchar);
00744           if (longind != NULL)
00745             *longind = option_index;
00746           if (pfound->flag)
00747             {
00748               *(pfound->flag) = pfound->val;
00749               return 0;
00750             }
00751           return pfound->val;
00752         }
00753 
00754       /* Can't find it as a long option.  If this is not getopt_long_only,
00755          or the option starts with '--' or is not a valid short
00756          option, then it's an error.
00757          Otherwise interpret it as a short option.  */
00758       if (!long_only || argv[optind][1] == '-'
00759           || my_index (optstring, *nextchar) == NULL)
00760         {
00761           if (print_errors)
00762             {
00763               if (argv[optind][1] == '-')
00764                 /* --option */
00765                 fprintf (stderr, _("%s: unrecognized option `--%s'\n"),
00766                          argv[0], nextchar);
00767               else
00768                 /* +option or -option */
00769                 fprintf (stderr, _("%s: unrecognized option `%c%s'\n"),
00770                          argv[0], argv[optind][0], nextchar);
00771             }
00772           nextchar = (char *) "";
00773           optind++;
00774           optopt = 0;
00775           return '?';
00776         }
00777     }
00778 
00779   /* Look at and handle the next short option-character.  */
00780 
00781   {
00782     char c = *nextchar++;
00783     char *temp = my_index (optstring, c);
00784 
00785     /* Increment `optind' when we start to process its last character.  */
00786     if (*nextchar == '\0')
00787       ++optind;
00788 
00789     if (temp == NULL || c == ':')
00790       {
00791         if (print_errors)
00792           {
00793             if (posixly_correct)
00794               /* 1003.2 specifies the format of this message.  */
00795               fprintf (stderr, _("%s: illegal option -- %c\n"),
00796                        argv[0], c);
00797             else
00798               fprintf (stderr, _("%s: invalid option -- %c\n"),
00799                        argv[0], c);
00800           }
00801         optopt = c;
00802         return '?';
00803       }
00804     /* Convenience. Treat POSIX -W foo same as long option --foo */
00805     if (temp[0] == 'W' && temp[1] == ';')
00806       {
00807         char *nameend;
00808         const struct option *p;
00809         const struct option *pfound = NULL;
00810         int exact = 0;
00811         int ambig = 0;
00812         int indfound = 0;
00813         int option_index;
00814 
00815         /* This is an option that requires an argument.  */
00816         if (*nextchar != '\0')
00817           {
00818             optarg = nextchar;
00819             /* If we end this ARGV-element by taking the rest as an arg,
00820                we must advance to the next element now.  */
00821             optind++;
00822           }
00823         else if (optind == argc)
00824           {
00825             if (print_errors)
00826               {
00827                 /* 1003.2 specifies the format of this message.  */
00828                 fprintf (stderr, _("%s: option requires an argument -- %c\n"),
00829                          argv[0], c);
00830               }
00831             optopt = c;
00832             if (optstring[0] == ':')
00833               c = ':';
00834             else
00835               c = '?';
00836             return c;
00837           }
00838         else
00839           /* We already incremented `optind' once;
00840              increment it again when taking next ARGV-elt as argument.  */
00841           optarg = argv[optind++];
00842 
00843         /* optarg is now the argument, see if it's in the
00844            table of longopts.  */
00845 
00846         for (nextchar = nameend = optarg; *nameend && *nameend != '='; nameend++)
00847           /* Do nothing.  */ ;
00848 
00849         /* Test all long options for either exact match
00850            or abbreviated matches.  */
00851         for (p = longopts, option_index = 0; p->name; p++, option_index++)
00852           if (!strncmp (p->name, nextchar, nameend - nextchar))
00853             {
00854               if ((unsigned int) (nameend - nextchar) == strlen (p->name))
00855                 {
00856                   /* Exact match found.  */
00857                   pfound = p;
00858                   indfound = option_index;
00859                   exact = 1;
00860                   break;
00861                 }
00862               else if (pfound == NULL)
00863                 {
00864                   /* First nonexact match found.  */
00865                   pfound = p;
00866                   indfound = option_index;
00867                 }
00868               else
00869                 /* Second or later nonexact match found.  */
00870                 ambig = 1;
00871             }
00872         if (ambig && !exact)
00873           {
00874             if (print_errors)
00875               fprintf (stderr, _("%s: option `-W %s' is ambiguous\n"),
00876                        argv[0], argv[optind]);
00877             nextchar += strlen (nextchar);
00878             optind++;
00879             return '?';
00880           }
00881         if (pfound != NULL)
00882           {
00883             option_index = indfound;
00884             if (*nameend)
00885               {
00886                 /* Don't test has_arg with >, because some C compilers don't
00887                    allow it to be used on enums.  */
00888                 if (pfound->has_arg)
00889                   optarg = nameend + 1;
00890                 else
00891                   {
00892                     if (print_errors)
00893                       fprintf (stderr, _("%s: option `-W %s' doesn't allow an argument\n"),
00894                                argv[0], pfound->name);
00895 
00896                     nextchar += strlen (nextchar);
00897                     return '?';
00898                   }
00899               }
00900             else if (pfound->has_arg == 1)
00901               {
00902                 if (optind < argc)
00903                   optarg = argv[optind++];
00904                 else
00905                   {
00906                     if (print_errors)
00907                       fprintf (stderr,
00908                                _("%s: option `%s' requires an argument\n"),
00909                                argv[0], argv[optind - 1]);
00910                     nextchar += strlen (nextchar);
00911                     return optstring[0] == ':' ? ':' : '?';
00912                   }
00913               }
00914             nextchar += strlen (nextchar);
00915             if (longind != NULL)
00916               *longind = option_index;
00917             if (pfound->flag)
00918               {
00919                 *(pfound->flag) = pfound->val;
00920                 return 0;
00921               }
00922             return pfound->val;
00923           }
00924           nextchar = NULL;
00925           return 'W';   /* Let the application handle it.   */
00926       }
00927     if (temp[1] == ':')
00928       {
00929         if (temp[2] == ':')
00930           {
00931             /* This is an option that accepts an argument optionally.  */
00932             if (*nextchar != '\0')
00933               {
00934                 optarg = nextchar;
00935                 optind++;
00936               }
00937             else
00938               optarg = NULL;
00939             nextchar = NULL;
00940           }
00941         else
00942           {
00943             /* This is an option that requires an argument.  */
00944             if (*nextchar != '\0')
00945               {
00946                 optarg = nextchar;
00947                 /* If we end this ARGV-element by taking the rest as an arg,
00948                    we must advance to the next element now.  */
00949                 optind++;
00950               }
00951             else if (optind == argc)
00952               {
00953                 if (print_errors)
00954                   {
00955                     /* 1003.2 specifies the format of this message.  */
00956                     fprintf (stderr,
00957                              _("%s: option requires an argument -- %c\n"),
00958                              argv[0], c);
00959                   }
00960                 optopt = c;
00961                 if (optstring[0] == ':')
00962                   c = ':';
00963                 else
00964                   c = '?';
00965               }
00966             else
00967               /* We already incremented `optind' once;
00968                  increment it again when taking next ARGV-elt as argument.  */
00969               optarg = argv[optind++];
00970             nextchar = NULL;
00971           }
00972       }
00973     return c;
00974   }
00975 }
00976 
00977 int
00978 getopt (argc, argv, optstring)
00979      int argc;
00980      char *const *argv;
00981      const char *optstring;
00982 {
00983   return _getopt_internal (argc, argv, optstring,
00984                            (const struct option *) 0,
00985                            (int *) 0,
00986                            0);
00987 }
00988 
00989 #endif  /* Not ELIDE_CODE.  */
00990 
00991 #ifdef TEST
00992 
00993 /* Compile with -DTEST to make an executable for use in testing
00994    the above definition of `getopt'.  */
00995 
00996 int
00997 main (argc, argv)
00998      int argc;
00999      char **argv;
01000 {
01001   int c;
01002   int digit_optind = 0;
01003 
01004   while (1)
01005     {
01006       int this_option_optind = optind ? optind : 1;
01007 
01008       c = getopt (argc, argv, "abc:d:0123456789");
01009       if (c == -1)
01010         break;
01011 
01012       switch (c)
01013         {
01014         case '0':
01015         case '1':
01016         case '2':
01017         case '3':
01018         case '4':
01019         case '5':
01020         case '6':
01021         case '7':
01022         case '8':
01023         case '9':
01024           if (digit_optind != 0 && digit_optind != this_option_optind)
01025             printf ("digits occur in two different argv-elements.\n");
01026           digit_optind = this_option_optind;
01027           printf ("option %c\n", c);
01028           break;
01029 
01030         case 'a':
01031           printf ("option a\n");
01032           break;
01033 
01034         case 'b':
01035           printf ("option b\n");
01036           break;
01037 
01038         case 'c':
01039           printf ("option c with value `%s'\n", optarg);
01040           break;
01041 
01042         case '?':
01043           break;
01044 
01045         default:
01046           printf ("?? getopt returned character code 0%o ??\n", c);
01047         }
01048     }
01049 
01050   if (optind < argc)
01051     {
01052       printf ("non-option ARGV-elements: ");
01053       while (optind < argc)
01054         printf ("%s ", argv[optind++]);
01055       printf ("\n");
01056     }
01057 
01058   exit (0);
01059 }
01060 
01061 #endif /* TEST */
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Defines


portrait_painter
Author(s): Niklas Meinzer, Ina Baumgarten
autogenerated on Wed Dec 26 2012 16:00:43