getopt.c
上传用户:shenzhenrh
上传日期:2013-05-12
资源大小:2904k
文件大小:30k
源码类别:

信息检索与抽取

开发平台:

Unix_Linux

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