Main Page | Class List | Directories | File List | Class Members | File Members

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    Copyright (C) 1987,88,89,90,91,92,93,94,95,96,98,99,2000,2001,2002
00006         Free Software Foundation, Inc.
00007    This file is part of the GNU C Library.
00008 
00009    The GNU C Library is free software; you can redistribute it and/or
00010    modify it under the terms of the GNU Lesser General Public
00011    License as published by the Free Software Foundation; either
00012    version 2.1 of the 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    Lesser General Public License for more details.
00018 
00019    You should have received a copy of the GNU Lesser General Public
00020    License along with the GNU C Library; if not, write to the Free
00021    Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
00022    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 (HAVE_LIBINTL_H && ENABLE_NLS) || defined _LIBC
00082 #  include <libintl.h>
00083 #  ifndef _
00084 #   define _(msgid)     gettext (msgid)
00085 #  endif
00086 # else
00087 #  define _(msgid)      (msgid)
00088 # endif
00089 # if defined _LIBC && defined USE_IN_LIBIO
00090 #  include <wchar.h>
00091 # endif
00092 #endif
00093 
00094 #ifndef attribute_hidden
00095 # define attribute_hidden
00096 #endif
00097 
00098 /* This version of `getopt' appears to the caller like standard Unix `getopt'
00099    but it behaves differently for the user, since it allows the user
00100    to intersperse the options with the other arguments.
00101 
00102    As `getopt' works, it permutes the elements of ARGV so that,
00103    when it is done, all the options precede everything else.  Thus
00104    all application programs are extended to handle flexible argument order.
00105 
00106    Setting the environment variable POSIXLY_CORRECT disables permutation.
00107    Then the behavior is completely standard.
00108 
00109    GNU application programs can use a third alternative mode in which
00110    they can distinguish the relative order of options and other arguments.  */
00111 
00112 #include "getopt.h"
00113 
00114 /* For communication from `getopt' to the caller.
00115    When `getopt' finds an option that takes an argument,
00116    the argument value is returned here.
00117    Also, when `ordering' is RETURN_IN_ORDER,
00118    each non-option ARGV-element is returned here.  */
00119 
00120 char *optarg;
00121 
00122 /* Index in ARGV of the next element to be scanned.
00123    This is used for communication to and from the caller
00124    and for communication between successive calls to `getopt'.
00125 
00126    On entry to `getopt', zero means this is the first call; initialize.
00127 
00128    When `getopt' returns -1, this is the index of the first of the
00129    non-option elements that the caller should itself scan.
00130 
00131    Otherwise, `optind' communicates from one call to the next
00132    how much of ARGV has been scanned so far.  */
00133 
00134 /* 1003.2 says this must be 1 before any call.  */
00135 int optind = 1;
00136 
00137 /* Formerly, initialization of getopt depended on optind==0, which
00138    causes problems with re-calling getopt as programs generally don't
00139    know that. */
00140 
00141 int __getopt_initialized attribute_hidden;
00142 
00143 /* The next char to be scanned in the option-element
00144    in which the last option character we returned was found.
00145    This allows us to pick up the scan where we left off.
00146 
00147    If this is zero, or a null string, it means resume the scan
00148    by advancing to the next ARGV-element.  */
00149 
00150 static char *nextchar;
00151 
00152 /* Callers store zero here to inhibit the error message
00153    for unrecognized options.  */
00154 
00155 int opterr = 1;
00156 
00157 /* Set to an option character which was unrecognized.
00158    This must be initialized on some systems to avoid linking in the
00159    system's own getopt implementation.  */
00160 
00161 int optopt = '?';
00162 
00163 /* Describe how to deal with options that follow non-option ARGV-elements.
00164 
00165    If the caller did not specify anything,
00166    the default is REQUIRE_ORDER if the environment variable
00167    POSIXLY_CORRECT is defined, PERMUTE otherwise.
00168 
00169    REQUIRE_ORDER means don't recognize them as options;
00170    stop option processing when the first non-option is seen.
00171    This is what Unix does.
00172    This mode of operation is selected by either setting the environment
00173    variable POSIXLY_CORRECT, or using `+' as the first character
00174    of the list of option characters.
00175 
00176    PERMUTE is the default.  We permute the contents of ARGV as we scan,
00177    so that eventually all the non-options are at the end.  This allows options
00178    to be given in any order, even with programs that were not written to
00179    expect this.
00180 
00181    RETURN_IN_ORDER is an option available to programs that were written
00182    to expect options and other ARGV-elements in any order and that care about
00183    the ordering of the two.  We describe each non-option ARGV-element
00184    as if it were the argument of an option with character code 1.
00185    Using `-' as the first character of the list of option characters
00186    selects this mode of operation.
00187 
00188    The special argument `--' forces an end of option-scanning regardless
00189    of the value of `ordering'.  In the case of RETURN_IN_ORDER, only
00190    `--' can cause `getopt' to return -1 with `optind' != ARGC.  */
00191 
00192 static enum
00193 {
00194   REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER
00195 } ordering;
00196 
00197 /* Value of POSIXLY_CORRECT environment variable.  */
00198 static char *posixly_correct;
00199 
00200 #ifdef  __GNU_LIBRARY__
00201 /* We want to avoid inclusion of string.h with non-GNU libraries
00202    because there are many ways it can cause trouble.
00203    On some systems, it contains special magic macros that don't work
00204    in GCC.  */
00205 # include <string.h>
00206 # define my_index       strchr
00207 #else
00208 
00209 # if HAVE_STRING_H
00210 #  include <string.h>
00211 # else
00212 #  include <strings.h>
00213 # endif
00214 
00215 /* Avoid depending on library functions or files
00216    whose names are inconsistent.  */
00217 
00218 #ifndef getenv
00219 extern char *getenv ();
00220 #endif
00221 
00222 static char *
00223 my_index (str, chr)
00224      const char *str;
00225      int chr;
00226 {
00227   while (*str)
00228     {
00229       if (*str == chr)
00230         return (char *) str;
00231       str++;
00232     }
00233   return 0;
00234 }
00235 
00236 /* If using GCC, we can safely declare strlen this way.
00237    If not using GCC, it is ok not to declare it.  */
00238 #ifdef __GNUC__
00239 /* Note that Motorola Delta 68k R3V7 comes with GCC but not stddef.h.
00240    That was relevant to code that was here before.  */
00241 # if (!defined __STDC__ || !__STDC__) && !defined strlen
00242 /* gcc with -traditional declares the built-in strlen to return int,
00243    and has done so at least since version 2.4.5. -- rms.  */
00244 extern int strlen (const char *);
00245 # endif /* not __STDC__ */
00246 #endif /* __GNUC__ */
00247 
00248 #endif /* not __GNU_LIBRARY__ */
00249 
00250 /* Handle permutation of arguments.  */
00251 
00252 /* Describe the part of ARGV that contains non-options that have
00253    been skipped.  `first_nonopt' is the index in ARGV of the first of them;
00254    `last_nonopt' is the index after the last of them.  */
00255 
00256 static int first_nonopt;
00257 static int last_nonopt;
00258 
00259 #ifdef _LIBC
00260 /* Stored original parameters.
00261    XXX This is no good solution.  We should rather copy the args so
00262    that we can compare them later.  But we must not use malloc(3).  */
00263 extern int __libc_argc;
00264 extern char **__libc_argv;
00265 
00266 /* Bash 2.0 gives us an environment variable containing flags
00267    indicating ARGV elements that should not be considered arguments.  */
00268 
00269 # ifdef USE_NONOPTION_FLAGS
00270 /* Defined in getopt_init.c  */
00271 extern char *__getopt_nonoption_flags;
00272 
00273 static int nonoption_flags_max_len;
00274 static int nonoption_flags_len;
00275 # endif
00276 
00277 # ifdef USE_NONOPTION_FLAGS
00278 #  define SWAP_FLAGS(ch1, ch2) \
00279   if (nonoption_flags_len > 0)                                                \
00280     {                                                                         \
00281       char __tmp = __getopt_nonoption_flags[ch1];                             \
00282       __getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2];          \
00283       __getopt_nonoption_flags[ch2] = __tmp;                                  \
00284     }
00285 # else
00286 #  define SWAP_FLAGS(ch1, ch2)
00287 # endif
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 #if defined _LIBC && defined USE_NONOPTION_FLAGS
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 #if defined _LIBC && defined USE_NONOPTION_FLAGS
00424   if (posixly_correct == NULL
00425       && argc == __libc_argc && argv == __libc_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 #if defined _LIBC && defined USE_NONOPTION_FLAGS
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             {
00689 #if defined _LIBC && defined USE_IN_LIBIO
00690               char *buf;
00691 
00692               if (__asprintf (&buf, _("%s: option `%s' is ambiguous\n"),
00693                               argv[0], argv[optind]) >= 0)
00694                 {
00695 
00696                   if (_IO_fwide (stderr, 0) > 0)
00697                     __fwprintf (stderr, L"%s", buf);
00698                   else
00699                     fputs (buf, stderr);
00700 
00701                   free (buf);
00702                 }
00703 #else
00704               fprintf (stderr, _("%s: option `%s' is ambiguous\n"),
00705                        argv[0], argv[optind]);
00706 #endif
00707             }
00708           nextchar += strlen (nextchar);
00709           optind++;
00710           optopt = 0;
00711           return '?';
00712         }
00713 
00714       if (pfound != NULL)
00715         {
00716           option_index = indfound;
00717           optind++;
00718           if (*nameend)
00719             {
00720               /* Don't test has_arg with >, because some C compilers don't
00721                  allow it to be used on enums.  */
00722               if (pfound->has_arg)
00723                 optarg = nameend + 1;
00724               else
00725                 {
00726                   if (print_errors)
00727                     {
00728 #if defined _LIBC && defined USE_IN_LIBIO
00729                       char *buf;
00730                       int n;
00731 #endif
00732 
00733                       if (argv[optind - 1][1] == '-')
00734                         {
00735                           /* --option */
00736 #if defined _LIBC && defined USE_IN_LIBIO
00737                           n = __asprintf (&buf, _("\
00738 %s: option `--%s' doesn't allow an argument\n"),
00739                                           argv[0], pfound->name);
00740 #else
00741                           fprintf (stderr, _("\
00742 %s: option `--%s' doesn't allow an argument\n"),
00743                                    argv[0], pfound->name);
00744 #endif
00745                         }
00746                       else
00747                         {
00748                           /* +option or -option */
00749 #if defined _LIBC && defined USE_IN_LIBIO
00750                           n = __asprintf (&buf, _("\
00751 %s: option `%c%s' doesn't allow an argument\n"),
00752                                           argv[0], argv[optind - 1][0],
00753                                           pfound->name);
00754 #else
00755                           fprintf (stderr, _("\
00756 %s: option `%c%s' doesn't allow an argument\n"),
00757                                    argv[0], argv[optind - 1][0], pfound->name);
00758 #endif
00759                         }
00760 
00761 #if defined _LIBC && defined USE_IN_LIBIO
00762                       if (n >= 0)
00763                         {
00764                           if (_IO_fwide (stderr, 0) > 0)
00765                             __fwprintf (stderr, L"%s", buf);
00766                           else
00767                             fputs (buf, stderr);
00768 
00769                           free (buf);
00770                         }
00771 #endif
00772                     }
00773 
00774                   nextchar += strlen (nextchar);
00775 
00776                   optopt = pfound->val;
00777                   return '?';
00778                 }
00779             }
00780           else if (pfound->has_arg == 1)
00781             {
00782               if (optind < argc)
00783                 optarg = argv[optind++];
00784               else
00785                 {
00786                   if (print_errors)
00787                     {
00788 #if defined _LIBC && defined USE_IN_LIBIO
00789                       char *buf;
00790 
00791                       if (__asprintf (&buf, _("\
00792 %s: option `%s' requires an argument\n"),
00793                                       argv[0], argv[optind - 1]) >= 0)
00794                         {
00795                           if (_IO_fwide (stderr, 0) > 0)
00796                             __fwprintf (stderr, L"%s", buf);
00797                           else
00798                             fputs (buf, stderr);
00799 
00800                           free (buf);
00801                         }
00802 #else
00803                       fprintf (stderr,
00804                                _("%s: option `%s' requires an argument\n"),
00805                                argv[0], argv[optind - 1]);
00806 #endif
00807                     }
00808                   nextchar += strlen (nextchar);
00809                   optopt = pfound->val;
00810                   return optstring[0] == ':' ? ':' : '?';
00811                 }
00812             }
00813           nextchar += strlen (nextchar);
00814           if (longind != NULL)
00815             *longind = option_index;
00816           if (pfound->flag)
00817             {
00818               *(pfound->flag) = pfound->val;
00819               return 0;
00820             }
00821           return pfound->val;
00822         }
00823 
00824       /* Can't find it as a long option.  If this is not getopt_long_only,
00825          or the option starts with '--' or is not a valid short
00826          option, then it's an error.
00827          Otherwise interpret it as a short option.  */
00828       if (!long_only || argv[optind][1] == '-'
00829           || my_index (optstring, *nextchar) == NULL)
00830         {
00831           if (print_errors)
00832             {
00833 #if defined _LIBC && defined USE_IN_LIBIO
00834               char *buf;
00835               int n;
00836 #endif
00837 
00838               if (argv[optind][1] == '-')
00839                 {
00840                   /* --option */
00841 #if defined _LIBC && defined USE_IN_LIBIO
00842                   n = __asprintf (&buf, _("%s: unrecognized option `--%s'\n"),
00843                                   argv[0], nextchar);
00844 #else
00845                   fprintf (stderr, _("%s: unrecognized option `--%s'\n"),
00846                            argv[0], nextchar);
00847 #endif
00848                 }
00849               else
00850                 {
00851                   /* +option or -option */
00852 #if defined _LIBC && defined USE_IN_LIBIO
00853                   n = __asprintf (&buf, _("%s: unrecognized option `%c%s'\n"),
00854                                   argv[0], argv[optind][0], nextchar);
00855 #else
00856                   fprintf (stderr, _("%s: unrecognized option `%c%s'\n"),
00857                            argv[0], argv[optind][0], nextchar);
00858 #endif
00859                 }
00860 
00861 #if defined _LIBC && defined USE_IN_LIBIO
00862               if (n >= 0)
00863                 {
00864                   if (_IO_fwide (stderr, 0) > 0)
00865                     __fwprintf (stderr, L"%s", buf);
00866                   else
00867                     fputs (buf, stderr);
00868 
00869                   free (buf);
00870                 }
00871 #endif
00872             }
00873           nextchar = (char *) "";
00874           optind++;
00875           optopt = 0;
00876           return '?';
00877         }
00878     }
00879 
00880   /* Look at and handle the next short option-character.  */
00881 
00882   {
00883     char c = *nextchar++;
00884     char *temp = my_index (optstring, c);
00885 
00886     /* Increment `optind' when we start to process its last character.  */
00887     if (*nextchar == '\0')
00888       ++optind;
00889 
00890     if (temp == NULL || c == ':')
00891       {
00892         if (print_errors)
00893           {
00894 #if defined _LIBC && defined USE_IN_LIBIO
00895               char *buf;
00896               int n;
00897 #endif
00898 
00899             if (posixly_correct)
00900               {
00901                 /* 1003.2 specifies the format of this message.  */
00902 #if defined _LIBC && defined USE_IN_LIBIO
00903                 n = __asprintf (&buf, _("%s: illegal option -- %c\n"),
00904                                 argv[0], c);
00905 #else
00906                 fprintf (stderr, _("%s: illegal option -- %c\n"), argv[0], c);
00907 #endif
00908               }
00909             else
00910               {
00911 #if defined _LIBC && defined USE_IN_LIBIO
00912                 n = __asprintf (&buf, _("%s: invalid option -- %c\n"),
00913                                 argv[0], c);
00914 #else
00915                 fprintf (stderr, _("%s: invalid option -- %c\n"), argv[0], c);
00916 #endif
00917               }
00918 
00919 #if defined _LIBC && defined USE_IN_LIBIO
00920             if (n >= 0)
00921               {
00922                 if (_IO_fwide (stderr, 0) > 0)
00923                   __fwprintf (stderr, L"%s", buf);
00924                 else
00925                   fputs (buf, stderr);
00926 
00927                 free (buf);
00928               }
00929 #endif
00930           }
00931         optopt = c;
00932         return '?';
00933       }
00934     /* Convenience. Treat POSIX -W foo same as long option --foo */
00935     if (temp[0] == 'W' && temp[1] == ';')
00936       {
00937         char *nameend;
00938         const struct option *p;
00939         const struct option *pfound = NULL;
00940         int exact = 0;
00941         int ambig = 0;
00942         int indfound = 0;
00943         int option_index;
00944 
00945         /* This is an option that requires an argument.  */
00946         if (*nextchar != '\0')
00947           {
00948             optarg = nextchar;
00949             /* If we end this ARGV-element by taking the rest as an arg,
00950                we must advance to the next element now.  */
00951             optind++;
00952           }
00953         else if (optind == argc)
00954           {
00955             if (print_errors)
00956               {
00957                 /* 1003.2 specifies the format of this message.  */
00958 #if defined _LIBC && defined USE_IN_LIBIO
00959                 char *buf;
00960 
00961                 if (__asprintf (&buf,
00962                                 _("%s: option requires an argument -- %c\n"),
00963                                 argv[0], c) >= 0)
00964                   {
00965                     if (_IO_fwide (stderr, 0) > 0)
00966                       __fwprintf (stderr, L"%s", buf);
00967                     else
00968                       fputs (buf, stderr);
00969 
00970                     free (buf);
00971                   }
00972 #else
00973                 fprintf (stderr, _("%s: option requires an argument -- %c\n"),
00974                          argv[0], c);
00975 #endif
00976               }
00977             optopt = c;
00978             if (optstring[0] == ':')
00979               c = ':';
00980             else
00981               c = '?';
00982             return c;
00983           }
00984         else
00985           /* We already incremented `optind' once;
00986              increment it again when taking next ARGV-elt as argument.  */
00987           optarg = argv[optind++];
00988 
00989         /* optarg is now the argument, see if it's in the
00990            table of longopts.  */
00991 
00992         for (nextchar = nameend = optarg; *nameend && *nameend != '='; nameend++)
00993           /* Do nothing.  */ ;
00994 
00995         /* Test all long options for either exact match
00996            or abbreviated matches.  */
00997         for (p = longopts, option_index = 0; p->name; p++, option_index++)
00998           if (!strncmp (p->name, nextchar, nameend - nextchar))
00999             {
01000               if ((unsigned int) (nameend - nextchar) == strlen (p->name))
01001                 {
01002                   /* Exact match found.  */
01003                   pfound = p;
01004                   indfound = option_index;
01005                   exact = 1;
01006                   break;
01007                 }
01008               else if (pfound == NULL)
01009                 {
01010                   /* First nonexact match found.  */
01011                   pfound = p;
01012                   indfound = option_index;
01013                 }
01014               else
01015                 /* Second or later nonexact match found.  */
01016                 ambig = 1;
01017             }
01018         if (ambig && !exact)
01019           {
01020             if (print_errors)
01021               {
01022 #if defined _LIBC && defined USE_IN_LIBIO
01023                 char *buf;
01024 
01025                 if (__asprintf (&buf, _("%s: option `-W %s' is ambiguous\n"),
01026                                 argv[0], argv[optind]) >= 0)
01027                   {
01028                     if (_IO_fwide (stderr, 0) > 0)
01029                       __fwprintf (stderr, L"%s", buf);
01030                     else
01031                       fputs (buf, stderr);
01032 
01033                     free (buf);
01034                   }
01035 #else
01036                 fprintf (stderr, _("%s: option `-W %s' is ambiguous\n"),
01037                          argv[0], argv[optind]);
01038 #endif
01039               }
01040             nextchar += strlen (nextchar);
01041             optind++;
01042             return '?';
01043           }
01044         if (pfound != NULL)
01045           {
01046             option_index = indfound;
01047             if (*nameend)
01048               {
01049                 /* Don't test has_arg with >, because some C compilers don't
01050                    allow it to be used on enums.  */
01051                 if (pfound->has_arg)
01052                   optarg = nameend + 1;
01053                 else
01054                   {
01055                     if (print_errors)
01056                       {
01057 #if defined _LIBC && defined USE_IN_LIBIO
01058                         char *buf;
01059 
01060                         if (__asprintf (&buf, _("\
01061 %s: option `-W %s' doesn't allow an argument\n"),
01062                                         argv[0], pfound->name) >= 0)
01063                           {
01064                             if (_IO_fwide (stderr, 0) > 0)
01065                               __fwprintf (stderr, L"%s", buf);
01066                             else
01067                               fputs (buf, stderr);
01068 
01069                             free (buf);
01070                           }
01071 #else
01072                         fprintf (stderr, _("\
01073 %s: option `-W %s' doesn't allow an argument\n"),
01074                                  argv[0], pfound->name);
01075 #endif
01076                       }
01077 
01078                     nextchar += strlen (nextchar);
01079                     return '?';
01080                   }
01081               }
01082             else if (pfound->has_arg == 1)
01083               {
01084                 if (optind < argc)
01085                   optarg = argv[optind++];
01086                 else
01087                   {
01088                     if (print_errors)
01089                       {
01090 #if defined _LIBC && defined USE_IN_LIBIO
01091                         char *buf;
01092 
01093                         if (__asprintf (&buf, _("\
01094 %s: option `%s' requires an argument\n"),
01095                                         argv[0], argv[optind - 1]) >= 0)
01096                           {
01097                             if (_IO_fwide (stderr, 0) > 0)
01098                               __fwprintf (stderr, L"%s", buf);
01099                             else
01100                               fputs (buf, stderr);
01101 
01102                             free (buf);
01103                           }
01104 #else
01105                         fprintf (stderr,
01106                                  _("%s: option `%s' requires an argument\n"),
01107                                  argv[0], argv[optind - 1]);
01108 #endif
01109                       }
01110                     nextchar += strlen (nextchar);
01111                     return optstring[0] == ':' ? ':' : '?';
01112                   }
01113               }
01114             nextchar += strlen (nextchar);
01115             if (longind != NULL)
01116               *longind = option_index;
01117             if (pfound->flag)
01118               {
01119                 *(pfound->flag) = pfound->val;
01120                 return 0;
01121               }
01122             return pfound->val;
01123           }
01124           nextchar = NULL;
01125           return 'W';   /* Let the application handle it.   */
01126       }
01127     if (temp[1] == ':')
01128       {
01129         if (temp[2] == ':')
01130           {
01131             /* This is an option that accepts an argument optionally.  */
01132             if (*nextchar != '\0')
01133               {
01134                 optarg = nextchar;
01135                 optind++;
01136               }
01137             else
01138               optarg = NULL;
01139             nextchar = NULL;
01140           }
01141         else
01142           {
01143             /* This is an option that requires an argument.  */
01144             if (*nextchar != '\0')
01145               {
01146                 optarg = nextchar;
01147                 /* If we end this ARGV-element by taking the rest as an arg,
01148                    we must advance to the next element now.  */
01149                 optind++;
01150               }
01151             else if (optind == argc)
01152               {
01153                 if (print_errors)
01154                   {
01155                     /* 1003.2 specifies the format of this message.  */
01156 #if defined _LIBC && defined USE_IN_LIBIO
01157                     char *buf;
01158 
01159                     if (__asprintf (&buf, _("\
01160 %s: option requires an argument -- %c\n"),
01161                                     argv[0], c) >= 0)
01162                       {
01163                         if (_IO_fwide (stderr, 0) > 0)
01164                           __fwprintf (stderr, L"%s", buf);
01165                         else
01166                           fputs (buf, stderr);
01167 
01168                         free (buf);
01169                       }
01170 #else
01171                     fprintf (stderr,
01172                              _("%s: option requires an argument -- %c\n"),
01173                              argv[0], c);
01174 #endif
01175                   }
01176                 optopt = c;
01177                 if (optstring[0] == ':')
01178                   c = ':';
01179                 else
01180                   c = '?';
01181               }
01182             else
01183               /* We already incremented `optind' once;
01184                  increment it again when taking next ARGV-elt as argument.  */
01185               optarg = argv[optind++];
01186             nextchar = NULL;
01187           }
01188       }
01189     return c;
01190   }
01191 }
01192 
01193 int
01194 getopt (argc, argv, optstring)
01195      int argc;
01196      char *const *argv;
01197      const char *optstring;
01198 {
01199   return _getopt_internal (argc, argv, optstring,
01200                            (const struct option *) 0,
01201                            (int *) 0,
01202                            0);
01203 }
01204 
01205 #endif  /* Not ELIDE_CODE.  */
01206 
01207 #ifdef TEST
01208 
01209 /* Compile with -DTEST to make an executable for use in testing
01210    the above definition of `getopt'.  */
01211 
01212 int
01213 main (argc, argv)
01214      int argc;
01215      char **argv;
01216 {
01217   int c;
01218   int digit_optind = 0;
01219 
01220   while (1)
01221     {
01222       int this_option_optind = optind ? optind : 1;
01223 
01224       c = getopt (argc, argv, "abc:d:0123456789");
01225       if (c == -1)
01226         break;
01227 
01228       switch (c)
01229         {
01230         case '0':
01231         case '1':
01232         case '2':
01233         case '3':
01234         case '4':
01235         case '5':
01236         case '6':
01237         case '7':
01238         case '8':
01239         case '9':
01240           if (digit_optind != 0 && digit_optind != this_option_optind)
01241             printf ("digits occur in two different argv-elements.\n");
01242           digit_optind = this_option_optind;
01243           printf ("option %c\n", c);
01244           break;
01245 
01246         case 'a':
01247           printf ("option a\n");
01248           break;
01249 
01250         case 'b':
01251           printf ("option b\n");
01252           break;
01253 
01254         case 'c':
01255           printf ("option c with value `%s'\n", optarg);
01256           break;
01257 
01258         case '?':
01259           break;
01260 
01261         default:
01262           printf ("?? getopt returned character code 0%o ??\n", c);
01263         }
01264     }
01265 
01266   if (optind < argc)
01267     {
01268       printf ("non-option ARGV-elements: ");
01269       while (optind < argc)
01270         printf ("%s ", argv[optind++]);
01271       printf ("\n");
01272     }
01273 
01274   exit (0);
01275 }
01276 
01277 #endif /* TEST */

© sourcejam.com 2005-2008