LibOFX: getopt.c Source File

- Main Page
- Namespaces
- Data Structures
- Files
- Related Pages

- File List
- Globals

# getopt.c

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