Subversion Repositories Kolibri OS

Rev

Rev 6132 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | Download | RSS feed

  1. /* Getopt for GNU.
  2.    NOTE: getopt is now part of the C library, so if you don't know what
  3.    "Keep this file name-space clean" means, talk to drepper@gnu.org
  4.    before changing it!
  5.  
  6.    Copyright (C) 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995,
  7.    1996, 1997, 1998, 2005 Free Software Foundation, Inc.
  8.  
  9.    NOTE: This source is derived from an old version taken from the GNU C
  10.    Library (glibc).
  11.  
  12.    This program is free software; you can redistribute it and/or modify it
  13.    under the terms of the GNU General Public License as published by the
  14.    Free Software Foundation; either version 2, or (at your option) any
  15.    later version.
  16.  
  17.    This program is distributed in the hope that it will be useful,
  18.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  19.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  20.    GNU General Public License for more details.
  21.  
  22.    You should have received a copy of the GNU General Public License
  23.    along with this program; if not, write to the Free Software
  24.    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301,
  25.    USA.  */
  26. /* This tells Alpha OSF/1 not to define a getopt prototype in <stdio.h>.
  27.    Ditto for AIX 3.2 and <stdlib.h>.  */
  28. #ifndef _NO_PROTO
  29. # define _NO_PROTO
  30. #endif
  31.  
  32. #ifdef HAVE_CONFIG_H
  33. # include <config.h>
  34. #endif
  35.  
  36. #if !defined __STDC__ || !__STDC__
  37. /* This is a separate conditional since some stdc systems
  38.    reject `defined (const)'.  */
  39. # ifndef const
  40. #  define const
  41. # endif
  42. #endif
  43.  
  44. #include "ansidecl.h"
  45. #define  NULL (void*)0
  46.  
  47. //#include <stdio.h>
  48.  
  49. /* Comment out all this code if we are using the GNU C Library, and are not
  50.    actually compiling the library itself.  This code is part of the GNU C
  51.    Library, but also included in many other GNU distributions.  Compiling
  52.    and linking in this code is a waste when using the GNU C library
  53.    (especially if it is a shared library).  Rather than having every GNU
  54.    program understand `configure --with-gnu-libc' and omit the object files,
  55.    it is simpler to just do this in the source for each such file.  */
  56.  
  57. #define GETOPT_INTERFACE_VERSION 2
  58. #if !defined _LIBC && defined __GLIBC__ && __GLIBC__ >= 2
  59. # include <gnu-versions.h>
  60. # if _GNU_GETOPT_INTERFACE_VERSION == GETOPT_INTERFACE_VERSION
  61. #  define ELIDE_CODE
  62. # endif
  63. #endif
  64.  
  65. #ifndef ELIDE_CODE
  66.  
  67.  
  68. /* This needs to come after some library #include
  69.    to get __GNU_LIBRARY__ defined.  */
  70. #ifdef  __GNU_LIBRARY__
  71. /* Don't include stdlib.h for non-GNU C libraries because some of them
  72.    contain conflicting prototypes for getopt.  */
  73. # include <stdlib.h>
  74. # include <unistd.h>
  75. #endif  /* GNU C library.  */
  76.  
  77. #ifdef VMS
  78. # include <unixlib.h>
  79. # if HAVE_STRING_H - 0
  80. #  include <string.h>
  81. # endif
  82. #endif
  83.  
  84. #define strlen __builtin_strlen
  85.  
  86. #  define _(msgid)  (msgid)
  87.  
  88. /* This version of `getopt' appears to the caller like standard Unix `getopt'
  89.    but it behaves differently for the user, since it allows the user
  90.    to intersperse the options with the other arguments.
  91.  
  92.    As `getopt' works, it permutes the elements of ARGV so that,
  93.    when it is done, all the options precede everything else.  Thus
  94.    all application programs are extended to handle flexible argument order.
  95.  
  96.    Setting the environment variable POSIXLY_CORRECT disables permutation.
  97.    Then the behavior is completely standard.
  98.  
  99.    GNU application programs can use a third alternative mode in which
  100.    they can distinguish the relative order of options and other arguments.  */
  101.  
  102. #include "getopt.h"
  103.  
  104. /* For communication from `getopt' to the caller.
  105.    When `getopt' finds an option that takes an argument,
  106.    the argument value is returned here.
  107.    Also, when `ordering' is RETURN_IN_ORDER,
  108.    each non-option ARGV-element is returned here.  */
  109.  
  110. char *optarg = NULL;
  111.  
  112. /* Index in ARGV of the next element to be scanned.
  113.    This is used for communication to and from the caller
  114.    and for communication between successive calls to `getopt'.
  115.  
  116.    On entry to `getopt', zero means this is the first call; initialize.
  117.  
  118.    When `getopt' returns -1, this is the index of the first of the
  119.    non-option elements that the caller should itself scan.
  120.  
  121.    Otherwise, `optind' communicates from one call to the next
  122.    how much of ARGV has been scanned so far.  */
  123.  
  124. /* 1003.2 says this must be 1 before any call.  */
  125. int optind = 1;
  126.  
  127. /* Formerly, initialization of getopt depended on optind==0, which
  128.    causes problems with re-calling getopt as programs generally don't
  129.    know that. */
  130.  
  131. int __getopt_initialized = 0;
  132.  
  133. /* The next char to be scanned in the option-element
  134.    in which the last option character we returned was found.
  135.    This allows us to pick up the scan where we left off.
  136.  
  137.    If this is zero, or a null string, it means resume the scan
  138.    by advancing to the next ARGV-element.  */
  139.  
  140. static char *nextchar;
  141.  
  142. /* Callers store zero here to inhibit the error message
  143.    for unrecognized options.  */
  144.  
  145. int opterr = 1;
  146.  
  147. /* Set to an option character which was unrecognized.
  148.    This must be initialized on some systems to avoid linking in the
  149.    system's own getopt implementation.  */
  150.  
  151. int optopt = '?';
  152.  
  153. /* Describe how to deal with options that follow non-option ARGV-elements.
  154.  
  155.    If the caller did not specify anything,
  156.    the default is REQUIRE_ORDER if the environment variable
  157.    POSIXLY_CORRECT is defined, PERMUTE otherwise.
  158.  
  159.    REQUIRE_ORDER means don't recognize them as options;
  160.    stop option processing when the first non-option is seen.
  161.    This is what Unix does.
  162.    This mode of operation is selected by either setting the environment
  163.    variable POSIXLY_CORRECT, or using `+' as the first character
  164.    of the list of option characters.
  165.  
  166.    PERMUTE is the default.  We permute the contents of ARGV as we scan,
  167.    so that eventually all the non-options are at the end.  This allows options
  168.    to be given in any order, even with programs that were not written to
  169.    expect this.
  170.  
  171.    RETURN_IN_ORDER is an option available to programs that were written
  172.    to expect options and other ARGV-elements in any order and that care about
  173.    the ordering of the two.  We describe each non-option ARGV-element
  174.    as if it were the argument of an option with character code 1.
  175.    Using `-' as the first character of the list of option characters
  176.    selects this mode of operation.
  177.  
  178.    The special argument `--' forces an end of option-scanning regardless
  179.    of the value of `ordering'.  In the case of RETURN_IN_ORDER, only
  180.    `--' can cause `getopt' to return -1 with `optind' != ARGC.  */
  181.  
  182. static enum
  183. {
  184.   REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER
  185. } ordering;
  186.  
  187. /* Value of POSIXLY_CORRECT environment variable.  */
  188. static char *posixly_correct;
  189. #ifdef  __GNU_LIBRARY__
  190. /* We want to avoid inclusion of string.h with non-GNU libraries
  191.    because there are many ways it can cause trouble.
  192.    On some systems, it contains special magic macros that don't work
  193.    in GCC.  */
  194. # include <string.h>
  195. # define my_index       strchr
  196. #else
  197.  
  198. # if HAVE_STRING_H
  199. #  include <string.h>
  200. # else
  201. #  if HAVE_STRINGS_H
  202. #   include <strings.h>
  203. #  endif
  204. # endif
  205.  
  206. /* Avoid depending on library functions or files
  207.    whose names are inconsistent.  */
  208.  
  209. #if HAVE_STDLIB_H && HAVE_DECL_GETENV
  210. #  include <stdlib.h>
  211. #elif !defined(getenv)
  212. #  ifdef __cplusplus
  213. extern "C" {
  214. #  endif /* __cplusplus */
  215. extern char *getenv (const char *);
  216. #  ifdef __cplusplus
  217. }
  218. #  endif /* __cplusplus */
  219. #endif
  220.  
  221. static char *
  222. my_index (const char *str, int chr)
  223. {
  224.   while (*str)
  225.     {
  226.       if (*str == chr)
  227.         return (char *) str;
  228.       str++;
  229.     }
  230.   return 0;
  231. }
  232.  
  233. /* If using GCC, we can safely declare strlen this way.
  234.    If not using GCC, it is ok not to declare it.  */
  235. #ifdef __GNUC__
  236. /* Note that Motorola Delta 68k R3V7 comes with GCC but not stddef.h.
  237.    That was relevant to code that was here before.  */
  238. # if (!defined __STDC__ || !__STDC__) && !defined strlen
  239. /* gcc with -traditional declares the built-in strlen to return int,
  240.    and has done so at least since version 2.4.5. -- rms.  */
  241. extern int strlen (const char *);
  242. # endif /* not __STDC__ */
  243. #endif /* __GNUC__ */
  244.  
  245. #endif /* not __GNU_LIBRARY__ */
  246. /* Handle permutation of arguments.  */
  247.  
  248. /* Describe the part of ARGV that contains non-options that have
  249.    been skipped.  `first_nonopt' is the index in ARGV of the first of them;
  250.    `last_nonopt' is the index after the last of them.  */
  251.  
  252. static int first_nonopt;
  253. static int last_nonopt;
  254.  
  255. #ifdef _LIBC
  256. /* Bash 2.0 gives us an environment variable containing flags
  257.    indicating ARGV elements that should not be considered arguments.  */
  258.  
  259. /* Defined in getopt_init.c  */
  260. extern char *__getopt_nonoption_flags;
  261.  
  262. static int nonoption_flags_max_len;
  263. static int nonoption_flags_len;
  264.  
  265. static int original_argc;
  266. static char *const *original_argv;
  267.  
  268. /* Make sure the environment variable bash 2.0 puts in the environment
  269.    is valid for the getopt call we must make sure that the ARGV passed
  270.    to getopt is that one passed to the process.  */
  271. static void
  272. __attribute__ ((unused))
  273. store_args_and_env (int argc, char *const *argv)
  274. {
  275.   /* XXX This is no good solution.  We should rather copy the args so
  276.      that we can compare them later.  But we must not use malloc(3).  */
  277.   original_argc = argc;
  278.   original_argv = argv;
  279. }
  280. # ifdef text_set_element
  281. text_set_element (__libc_subinit, store_args_and_env);
  282. # endif /* text_set_element */
  283.  
  284. # define SWAP_FLAGS(ch1, ch2) \
  285.   if (nonoption_flags_len > 0)                                                \
  286.     {                                                                         \
  287.       char __tmp = __getopt_nonoption_flags[ch1];                             \
  288.       __getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2];          \
  289.       __getopt_nonoption_flags[ch2] = __tmp;                                  \
  290.     }
  291. #else   /* !_LIBC */
  292. # define SWAP_FLAGS(ch1, ch2)
  293. #endif  /* _LIBC */
  294.  
  295. /* Exchange two adjacent subsequences of ARGV.
  296.    One subsequence is elements [first_nonopt,last_nonopt)
  297.    which contains all the non-options that have been skipped so far.
  298.    The other is elements [last_nonopt,optind), which contains all
  299.    the options processed since those non-options were skipped.
  300.  
  301.    `first_nonopt' and `last_nonopt' are relocated so that they describe
  302.    the new indices of the non-options in ARGV after they are moved.  */
  303.  
  304. #if defined __STDC__ && __STDC__
  305. static void exchange (char **);
  306. #endif
  307.  
  308. static void
  309. exchange (char **argv)
  310. {
  311.   int bottom = first_nonopt;
  312.   int middle = last_nonopt;
  313.   int top = optind;
  314.   char *tem;
  315.  
  316.   /* Exchange the shorter segment with the far end of the longer segment.
  317.      That puts the shorter segment into the right place.
  318.      It leaves the longer segment in the right place overall,
  319.      but it consists of two parts that need to be swapped next.  */
  320.  
  321. #ifdef _LIBC
  322.   /* First make sure the handling of the `__getopt_nonoption_flags'
  323.      string can work normally.  Our top argument must be in the range
  324.      of the string.  */
  325.   if (nonoption_flags_len > 0 && top >= nonoption_flags_max_len)
  326.     {
  327.       /* We must extend the array.  The user plays games with us and
  328.          presents new arguments.  */
  329.       char *new_str = (char *) malloc (top + 1);
  330.       if (new_str == NULL)
  331.         nonoption_flags_len = nonoption_flags_max_len = 0;
  332.       else
  333.         {
  334.           memset (mempcpy (new_str, __getopt_nonoption_flags,
  335.                            nonoption_flags_max_len),
  336.                   '\0', top + 1 - nonoption_flags_max_len);
  337.           nonoption_flags_max_len = top + 1;
  338.           __getopt_nonoption_flags = new_str;
  339.         }
  340.     }
  341. #endif
  342.  
  343.   while (top > middle && middle > bottom)
  344.     {
  345.       if (top - middle > middle - bottom)
  346.         {
  347.           /* Bottom segment is the short one.  */
  348.           int len = middle - bottom;
  349.           register int i;
  350.  
  351.           /* Swap it with the top part of the top segment.  */
  352.           for (i = 0; i < len; i++)
  353.             {
  354.               tem = argv[bottom + i];
  355.               argv[bottom + i] = argv[top - (middle - bottom) + i];
  356.               argv[top - (middle - bottom) + i] = tem;
  357.               SWAP_FLAGS (bottom + i, top - (middle - bottom) + i);
  358.             }
  359.           /* Exclude the moved bottom segment from further swapping.  */
  360.           top -= len;
  361.         }
  362.       else
  363.         {
  364.           /* Top segment is the short one.  */
  365.           int len = top - middle;
  366.           register int i;
  367.  
  368.           /* Swap it with the bottom part of the bottom segment.  */
  369.           for (i = 0; i < len; i++)
  370.             {
  371.               tem = argv[bottom + i];
  372.               argv[bottom + i] = argv[middle + i];
  373.               argv[middle + i] = tem;
  374.               SWAP_FLAGS (bottom + i, middle + i);
  375.             }
  376.           /* Exclude the moved top segment from further swapping.  */
  377.           bottom += len;
  378.         }
  379.     }
  380.  
  381.   /* Update records for the slots the non-options now occupy.  */
  382.  
  383.   first_nonopt += (optind - last_nonopt);
  384.   last_nonopt = optind;
  385. }
  386.  
  387. /* Initialize the internal data when the first call is made.  */
  388.  
  389. #if defined __STDC__ && __STDC__
  390. static const char *_getopt_initialize (int, char *const *, const char *);
  391. #endif
  392. static const char *
  393. _getopt_initialize (int argc ATTRIBUTE_UNUSED,
  394.                     char *const *argv ATTRIBUTE_UNUSED,
  395.                     const char *optstring)
  396. {
  397.   /* Start processing options with ARGV-element 1 (since ARGV-element 0
  398.      is the program name); the sequence of previously skipped
  399.      non-option ARGV-elements is empty.  */
  400.  
  401.   first_nonopt = last_nonopt = optind;
  402.  
  403.   nextchar = NULL;
  404.  
  405.   posixly_correct = NULL;
  406.  
  407.   /* Determine how to handle the ordering of options and nonoptions.  */
  408.  
  409.   if (optstring[0] == '-')
  410.     {
  411.       ordering = RETURN_IN_ORDER;
  412.       ++optstring;
  413.     }
  414.   else if (optstring[0] == '+')
  415.     {
  416.       ordering = REQUIRE_ORDER;
  417.       ++optstring;
  418.     }
  419.   else if (posixly_correct != NULL)
  420.     ordering = REQUIRE_ORDER;
  421.   else
  422.     ordering = PERMUTE;
  423.  
  424. #ifdef _LIBC
  425.   if (posixly_correct == NULL
  426.       && argc == original_argc && argv == original_argv)
  427.     {
  428.       if (nonoption_flags_max_len == 0)
  429.         {
  430.           if (__getopt_nonoption_flags == NULL
  431.               || __getopt_nonoption_flags[0] == '\0')
  432.             nonoption_flags_max_len = -1;
  433.           else
  434.             {
  435.               const char *orig_str = __getopt_nonoption_flags;
  436.               int len = nonoption_flags_max_len = strlen (orig_str);
  437.               if (nonoption_flags_max_len < argc)
  438.                 nonoption_flags_max_len = argc;
  439.               __getopt_nonoption_flags =
  440.                 (char *) malloc (nonoption_flags_max_len);
  441.               if (__getopt_nonoption_flags == NULL)
  442.                 nonoption_flags_max_len = -1;
  443.               else
  444.                 memset (mempcpy (__getopt_nonoption_flags, orig_str, len),
  445.                         '\0', nonoption_flags_max_len - len);
  446.             }
  447.         }
  448.       nonoption_flags_len = nonoption_flags_max_len;
  449.     }
  450.   else
  451.     nonoption_flags_len = 0;
  452. #endif
  453.  
  454.   return optstring;
  455. }
  456. /* Scan elements of ARGV (whose length is ARGC) for option characters
  457.    given in OPTSTRING.
  458.  
  459.    If an element of ARGV starts with '-', and is not exactly "-" or "--",
  460.    then it is an option element.  The characters of this element
  461.    (aside from the initial '-') are option characters.  If `getopt'
  462.    is called repeatedly, it returns successively each of the option characters
  463.    from each of the option elements.
  464.  
  465.    If `getopt' finds another option character, it returns that character,
  466.    updating `optind' and `nextchar' so that the next call to `getopt' can
  467.    resume the scan with the following option character or ARGV-element.
  468.  
  469.    If there are no more option characters, `getopt' returns -1.
  470.    Then `optind' is the index in ARGV of the first ARGV-element
  471.    that is not an option.  (The ARGV-elements have been permuted
  472.    so that those that are not options now come last.)
  473.  
  474.    OPTSTRING is a string containing the legitimate option characters.
  475.    If an option character is seen that is not listed in OPTSTRING,
  476.    return '?' after printing an error message.  If you set `opterr' to
  477.    zero, the error message is suppressed but we still return '?'.
  478.  
  479.    If a char in OPTSTRING is followed by a colon, that means it wants an arg,
  480.    so the following text in the same ARGV-element, or the text of the following
  481.    ARGV-element, is returned in `optarg'.  Two colons mean an option that
  482.    wants an optional arg; if there is text in the current ARGV-element,
  483.    it is returned in `optarg', otherwise `optarg' is set to zero.
  484.  
  485.    If OPTSTRING starts with `-' or `+', it requests different methods of
  486.    handling the non-option ARGV-elements.
  487.    See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
  488.  
  489.    Long-named options begin with `--' instead of `-'.
  490.    Their names may be abbreviated as long as the abbreviation is unique
  491.    or is an exact match for some defined option.  If they have an
  492.    argument, it follows the option name in the same ARGV-element, separated
  493.    from the option name by a `=', or else the in next ARGV-element.
  494.    When `getopt' finds a long-named option, it returns 0 if that option's
  495.    `flag' field is nonzero, the value of the option's `val' field
  496.    if the `flag' field is zero.
  497.  
  498.    The elements of ARGV aren't really const, because we permute them.
  499.    But we pretend they're const in the prototype to be compatible
  500.    with other systems.
  501.  
  502.    LONGOPTS is a vector of `struct option' terminated by an
  503.    element containing a name which is zero.
  504.  
  505.    LONGIND returns the index in LONGOPT of the long-named option found.
  506.    It is only valid when a long-named option has been found by the most
  507.    recent call.
  508.  
  509.    If LONG_ONLY is nonzero, '-' as well as '--' can introduce
  510.    long-named options.  */
  511.  
  512. int
  513. _getopt_internal (int argc, char *const *argv, const char *optstring,
  514.                   const struct option *longopts,
  515.                   int *longind, int long_only)
  516. {
  517.     optarg = NULL;
  518.  
  519.     if (!__getopt_initialized)
  520.     {
  521.         optind = 0;
  522.         optstring = _getopt_initialize (argc, argv, optstring);
  523.         __getopt_initialized = 1;
  524.     }
  525.  
  526.   /* Test whether ARGV[optind] points to a non-option argument.
  527.      Either it does not have option syntax, or there is an environment flag
  528.      from the shell indicating it is not an option.  The later information
  529.      is only used when the used in the GNU libc.  */
  530. #ifdef _LIBC
  531. # define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0'       \
  532.                       || (optind < nonoption_flags_len                        \
  533.                           && __getopt_nonoption_flags[optind] == '1'))
  534. #else
  535. # define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0')
  536. #endif
  537.  
  538.   if (nextchar == NULL || *nextchar == '\0')
  539.     {
  540.       /* Advance to the next ARGV-element.  */
  541.  
  542.       /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
  543.          moved back by the user (who may also have changed the arguments).  */
  544.       if (last_nonopt > optind)
  545.         last_nonopt = optind;
  546.       if (first_nonopt > optind)
  547.         first_nonopt = optind;
  548.  
  549.       if (ordering == PERMUTE)
  550.         {
  551.           /* If we have just processed some options following some non-options,
  552.              exchange them so that the options come first.  */
  553.  
  554.           if (first_nonopt != last_nonopt && last_nonopt != optind)
  555.             exchange ((char **) argv);
  556.           else if (last_nonopt != optind)
  557.             first_nonopt = optind;
  558.  
  559.           /* Skip any additional non-options
  560.              and extend the range of non-options previously skipped.  */
  561.  
  562.           while (optind < argc && NONOPTION_P)
  563.             optind++;
  564.           last_nonopt = optind;
  565.         }
  566.  
  567.       /* The special ARGV-element `--' means premature end of options.
  568.          Skip it like a null option,
  569.          then exchange with previous non-options as if it were an option,
  570.          then skip everything else like a non-option.  */
  571.  
  572.       if (optind != argc && !strcmp (argv[optind], "--"))
  573.         {
  574.           optind++;
  575.  
  576.           if (first_nonopt != last_nonopt && last_nonopt != optind)
  577.             exchange ((char **) argv);
  578.           else if (first_nonopt == last_nonopt)
  579.             first_nonopt = optind;
  580.           last_nonopt = argc;
  581.  
  582.           optind = argc;
  583.         }
  584.  
  585.       /* If we have done all the ARGV-elements, stop the scan
  586.          and back over any non-options that we skipped and permuted.  */
  587.  
  588.       if (optind == argc)
  589.         {
  590.           /* Set the next-arg-index to point at the non-options
  591.              that we previously skipped, so the caller will digest them.  */
  592.           if (first_nonopt != last_nonopt)
  593.             optind = first_nonopt;
  594.           return -1;
  595.         }
  596.  
  597.       /* If we have come to a non-option and did not permute it,
  598.          either stop the scan or describe it to the caller and pass it by.  */
  599.  
  600.       if (NONOPTION_P)
  601.         {
  602.           if (ordering == REQUIRE_ORDER)
  603.             return -1;
  604.           optarg = argv[optind++];
  605.           return 1;
  606.         }
  607.  
  608.       /* We have found another option-ARGV-element.
  609.          Skip the initial punctuation.  */
  610.  
  611.       nextchar = (argv[optind] + 1
  612.                   + (longopts != NULL && argv[optind][1] == '-'));
  613.     }
  614.  
  615.   /* Decode the current option-ARGV-element.  */
  616.  
  617.   /* Check whether the ARGV-element is a long option.
  618.  
  619.      If long_only and the ARGV-element has the form "-f", where f is
  620.      a valid short option, don't consider it an abbreviated form of
  621.      a long option that starts with f.  Otherwise there would be no
  622.      way to give the -f short option.
  623.  
  624.      On the other hand, if there's a long option "fubar" and
  625.      the ARGV-element is "-fu", do consider that an abbreviation of
  626.      the long option, just like "--fu", and not "-f" with arg "u".
  627.  
  628.      This distinction seems to be the most useful approach.  */
  629.  
  630.   if (longopts != NULL
  631.       && (argv[optind][1] == '-'
  632.           || (long_only && (argv[optind][2] || !my_index (optstring, argv[optind][1])))))
  633.     {
  634.       char *nameend;
  635.       const struct option *p;
  636.       const struct option *pfound = NULL;
  637.       int exact = 0;
  638.       int ambig = 0;
  639.       int indfound = -1;
  640.       int option_index;
  641.  
  642.       for (nameend = nextchar; *nameend && *nameend != '='; nameend++)
  643.         /* Do nothing.  */ ;
  644.  
  645.       /* Test all long options for either exact match
  646.          or abbreviated matches.  */
  647.       for (p = longopts, option_index = 0; p->name; p++, option_index++)
  648.         if (!strncmp (p->name, nextchar, nameend - nextchar))
  649.           {
  650.             if ((unsigned int) (nameend - nextchar)
  651.                 == (unsigned int) strlen (p->name))
  652.               {
  653.                 /* Exact match found.  */
  654.                 pfound = p;
  655.                 indfound = option_index;
  656.                 exact = 1;
  657.                 break;
  658.               }
  659.             else if (pfound == NULL)
  660.               {
  661.                 /* First nonexact match found.  */
  662.                 pfound = p;
  663.                 indfound = option_index;
  664.               }
  665.             else
  666.               /* Second or later nonexact match found.  */
  667.               ambig = 1;
  668.           }
  669.  
  670.       if (ambig && !exact)
  671.         {
  672.           if (opterr)
  673.         printf ("%s: option `%s' is ambiguous\n",
  674.                      argv[0], argv[optind]);
  675.           nextchar += strlen (nextchar);
  676.           optind++;
  677.           optopt = 0;
  678.           return '?';
  679.         }
  680.  
  681.       if (pfound != NULL)
  682.         {
  683.           option_index = indfound;
  684.           optind++;
  685.           if (*nameend)
  686.             {
  687.               /* Don't test has_arg with >, because some C compilers don't
  688.                  allow it to be used on enums.  */
  689.               if (pfound->has_arg)
  690.                 optarg = nameend + 1;
  691.               else
  692.                 {
  693.                   if (opterr)
  694.                     {
  695.                       if (argv[optind - 1][1] == '-')
  696.                         /* --option */
  697.             printf ("%s: option `--%s' doesn't allow an argument\n",
  698.                                  argv[0], pfound->name);
  699.                       else
  700.                         /* +option or -option */
  701.             printf ("%s: option `%c%s' doesn't allow an argument\n",
  702.                                  argv[0], argv[optind - 1][0], pfound->name);
  703.  
  704.                       nextchar += strlen (nextchar);
  705.  
  706.                       optopt = pfound->val;
  707.                       return '?';
  708.                     }
  709.                 }
  710.             }
  711.           else if (pfound->has_arg == 1)
  712.             {
  713.               if (optind < argc)
  714.                 optarg = argv[optind++];
  715.               else
  716.                 {
  717.                   if (opterr)
  718.             printf ("%s: option `%s' requires an argument\n",
  719.                            argv[0], argv[optind - 1]);
  720.                   nextchar += strlen (nextchar);
  721.                   optopt = pfound->val;
  722.                   return optstring[0] == ':' ? ':' : '?';
  723.                 }
  724.             }
  725.           nextchar += strlen (nextchar);
  726.           if (longind != NULL)
  727.             *longind = option_index;
  728.           if (pfound->flag)
  729.             {
  730.               *(pfound->flag) = pfound->val;
  731.               return 0;
  732.             }
  733.           return pfound->val;
  734.         }
  735.  
  736.       /* Can't find it as a long option.  If this is not getopt_long_only,
  737.          or the option starts with '--' or is not a valid short
  738.          option, then it's an error.
  739.          Otherwise interpret it as a short option.  */
  740.       if (!long_only || argv[optind][1] == '-'
  741.           || my_index (optstring, *nextchar) == NULL)
  742.         {
  743.           if (opterr)
  744.             {
  745.               if (argv[optind][1] == '-')
  746.                 /* --option */
  747.         printf ("%s: unrecognized option `--%s'\n",
  748.                          argv[0], nextchar);
  749.               else
  750.                 /* +option or -option */
  751.         printf ("%s: unrecognized option `%c%s'\n",
  752.                          argv[0], argv[optind][0], nextchar);
  753.             }
  754.           nextchar = (char *) "";
  755.           optind++;
  756.           optopt = 0;
  757.           return '?';
  758.         }
  759.     }
  760.  
  761.   /* Look at and handle the next short option-character.  */
  762.  
  763.   {
  764.     char c = *nextchar++;
  765.     char *temp = my_index (optstring, c);
  766.  
  767.     /* Increment `optind' when we start to process its last character.  */
  768.     if (*nextchar == '\0')
  769.       ++optind;
  770.  
  771.     if (temp == NULL || c == ':')
  772.       {
  773.         if (opterr)
  774.           {
  775.             if (posixly_correct)
  776.               /* 1003.2 specifies the format of this message.  */
  777.           printf ("%s: illegal option -- %c\n",
  778.                        argv[0], c);
  779.             else
  780.           printf ("%s: invalid option -- %c\n",
  781.                        argv[0], c);
  782.           }
  783.         optopt = c;
  784.         return '?';
  785.       }
  786.     /* Convenience. Treat POSIX -W foo same as long option --foo */
  787.     if (temp[0] == 'W' && temp[1] == ';')
  788.       {
  789.         char *nameend;
  790.         const struct option *p;
  791.         const struct option *pfound = NULL;
  792.         int exact = 0;
  793.         int ambig = 0;
  794.         int indfound = 0;
  795.         int option_index;
  796.  
  797.         /* This is an option that requires an argument.  */
  798.         if (*nextchar != '\0')
  799.           {
  800.             optarg = nextchar;
  801.             /* If we end this ARGV-element by taking the rest as an arg,
  802.                we must advance to the next element now.  */
  803.             optind++;
  804.           }
  805.         else if (optind == argc)
  806.           {
  807.             if (opterr)
  808.               {
  809.                 /* 1003.2 specifies the format of this message.  */
  810.         printf ("%s: option requires an argument -- %c\n",
  811.                          argv[0], c);
  812.               }
  813.             optopt = c;
  814.             if (optstring[0] == ':')
  815.               c = ':';
  816.             else
  817.               c = '?';
  818.             return c;
  819.           }
  820.         else
  821.           /* We already incremented `optind' once;
  822.              increment it again when taking next ARGV-elt as argument.  */
  823.           optarg = argv[optind++];
  824.  
  825.         /* optarg is now the argument, see if it's in the
  826.            table of longopts.  */
  827.  
  828.         for (nextchar = nameend = optarg; *nameend && *nameend != '='; nameend++)
  829.           /* Do nothing.  */ ;
  830.  
  831.         /* Test all long options for either exact match
  832.            or abbreviated matches.  */
  833.         for (p = longopts, option_index = 0; p->name; p++, option_index++)
  834.           if (!strncmp (p->name, nextchar, nameend - nextchar))
  835.             {
  836.               if ((unsigned int) (nameend - nextchar) == strlen (p->name))
  837.                 {
  838.                   /* Exact match found.  */
  839.                   pfound = p;
  840.                   indfound = option_index;
  841.                   exact = 1;
  842.                   break;
  843.                 }
  844.               else if (pfound == NULL)
  845.                 {
  846.                   /* First nonexact match found.  */
  847.                   pfound = p;
  848.                   indfound = option_index;
  849.                 }
  850.               else
  851.                 /* Second or later nonexact match found.  */
  852.                 ambig = 1;
  853.             }
  854.         if (ambig && !exact)
  855.           {
  856.             if (opterr)
  857.           printf ("%s: option `-W %s' is ambiguous\n",
  858.                        argv[0], argv[optind]);
  859.             nextchar += strlen (nextchar);
  860.             optind++;
  861.             return '?';
  862.           }
  863.         if (pfound != NULL)
  864.           {
  865.             option_index = indfound;
  866.             if (*nameend)
  867.               {
  868.                 /* Don't test has_arg with >, because some C compilers don't
  869.                    allow it to be used on enums.  */
  870.                 if (pfound->has_arg)
  871.                   optarg = nameend + 1;
  872.                 else
  873.                   {
  874.                     if (opterr)
  875.               printf ("\%s: option `-W %s' doesn't allow an argument\n",
  876.                                argv[0], pfound->name);
  877.  
  878.                     nextchar += strlen (nextchar);
  879.                     return '?';
  880.                   }
  881.               }
  882.             else if (pfound->has_arg == 1)
  883.               {
  884.                 if (optind < argc)
  885.                   optarg = argv[optind++];
  886.                 else
  887.                   {
  888.                     if (opterr)
  889.               printf ("%s: option `%s' requires an argument\n",
  890.                                argv[0], argv[optind - 1]);
  891.                     nextchar += strlen (nextchar);
  892.                     return optstring[0] == ':' ? ':' : '?';
  893.                   }
  894.               }
  895.             nextchar += strlen (nextchar);
  896.             if (longind != NULL)
  897.               *longind = option_index;
  898.             if (pfound->flag)
  899.               {
  900.                 *(pfound->flag) = pfound->val;
  901.                 return 0;
  902.               }
  903.             return pfound->val;
  904.           }
  905.           nextchar = NULL;
  906.           return 'W';   /* Let the application handle it.   */
  907.       }
  908.     if (temp[1] == ':')
  909.       {
  910.         if (temp[2] == ':')
  911.           {
  912.             /* This is an option that accepts an argument optionally.  */
  913.             if (*nextchar != '\0')
  914.               {
  915.                 optarg = nextchar;
  916.                 optind++;
  917.               }
  918.             else
  919.               optarg = NULL;
  920.             nextchar = NULL;
  921.           }
  922.         else
  923.           {
  924.             /* This is an option that requires an argument.  */
  925.             if (*nextchar != '\0')
  926.               {
  927.                 optarg = nextchar;
  928.                 /* If we end this ARGV-element by taking the rest as an arg,
  929.                    we must advance to the next element now.  */
  930.                 optind++;
  931.               }
  932.             else if (optind == argc)
  933.               {
  934.                 if (opterr)
  935.                   {
  936.                     /* 1003.2 specifies the format of this message.  */
  937.             printf ("%s: option requires an argument -- %c\n",
  938.                            argv[0], c);
  939.                   }
  940.                 optopt = c;
  941.                 if (optstring[0] == ':')
  942.                   c = ':';
  943.                 else
  944.                   c = '?';
  945.               }
  946.             else
  947.               /* We already incremented `optind' once;
  948.                  increment it again when taking next ARGV-elt as argument.  */
  949.               optarg = argv[optind++];
  950.             nextchar = NULL;
  951.           }
  952.       }
  953.     return c;
  954.   }
  955. }
  956.  
  957. int
  958. getopt (int argc, char *const *argv, const char *optstring)
  959. {
  960.   return _getopt_internal (argc, argv, optstring,
  961.                            (const struct option *) 0,
  962.                            (int *) 0,
  963.                            0);
  964. }
  965.  
  966. #endif  /* Not ELIDE_CODE.  */
  967. #ifdef TEST
  968.  
  969. /* Compile with -DTEST to make an executable for use in testing
  970.    the above definition of `getopt'.  */
  971.  
  972. int
  973. main (int argc, char **argv)
  974. {
  975.   int c;
  976.   int digit_optind = 0;
  977.  
  978.   while (1)
  979.     {
  980.       int this_option_optind = optind ? optind : 1;
  981.  
  982.       c = getopt (argc, argv, "abc:d:0123456789");
  983.       if (c == -1)
  984.         break;
  985.  
  986.       switch (c)
  987.         {
  988.         case '0':
  989.         case '1':
  990.         case '2':
  991.         case '3':
  992.         case '4':
  993.         case '5':
  994.         case '6':
  995.         case '7':
  996.         case '8':
  997.         case '9':
  998.           if (digit_optind != 0 && digit_optind != this_option_optind)
  999.             printf ("digits occur in two different argv-elements.\n");
  1000.           digit_optind = this_option_optind;
  1001.           printf ("option %c\n", c);
  1002.           break;
  1003.  
  1004.         case 'a':
  1005.           printf ("option a\n");
  1006.           break;
  1007.  
  1008.         case 'b':
  1009.           printf ("option b\n");
  1010.           break;
  1011.  
  1012.         case 'c':
  1013.           printf ("option c with value `%s'\n", optarg);
  1014.           break;
  1015.  
  1016.         case '?':
  1017.           break;
  1018.  
  1019.         default:
  1020.           printf ("?? getopt returned character code 0%o ??\n", c);
  1021.         }
  1022.     }
  1023.  
  1024.   if (optind < argc)
  1025.     {
  1026.       printf ("non-option ARGV-elements: ");
  1027.       while (optind < argc)
  1028.         printf ("%s ", argv[optind++]);
  1029.       printf ("\n");
  1030.     }
  1031.  
  1032.   exit (0);
  1033. }
  1034.  
  1035. #endif /* TEST */
  1036.