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

Generated on Fri Jan 9 13:44:29 2009 for libextractor by  doxygen 1.5.1