getopt.c

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

Generated on Mon Jul 2 19:10:16 2007 for CanFestival by  doxygen 1.5.1