home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 35 Internet / 35-Internet.zip / fingercl.zip / getopt.c < prev    next >
C/C++ Source or Header  |  1997-08-29  |  22KB  |  681 lines

  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.  
  6.    Copyright (C) 1987, 88, 89, 90, 91, 1992 Free Software Foundation, Inc.
  7.  
  8.    This program is free software; you can redistribute it and/or modify it
  9.    under the terms of the GNU General Public License as published by the
  10.    Free Software Foundation; either version 2, or (at your option) any
  11.    later version.
  12.  
  13.    This program is distributed in the hope that it will be useful,
  14.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  15.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  16.    GNU General Public License for more details.
  17.  
  18.    You should have received a copy of the GNU General Public License
  19.    along with this program; if not, write to the Free Software
  20.    Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
  21.  
  22. /* AIX requires this to be the first thing in the file.  */
  23. #ifdef __GNUC__
  24. #define alloca __builtin_alloca
  25. #else /* not __GNUC__ */
  26. #if defined (HAVE_ALLOCA_H) || (defined(sparc) && (defined(sun) || (!defined(USG) && !defined(SVR4) && !defined(__svr4__))))
  27. #include <alloca.h>
  28. #else
  29. #ifdef _AIX
  30.  #pragma alloca
  31. #else
  32. char *alloca ();
  33. #endif
  34. #endif /* alloca.h */
  35. #endif /* not __GNUC__ */
  36.  
  37. #include <stdio.h>
  38. #include <strings.h>
  39.  
  40. /* This needs to come after some library #include
  41.    to get __GNU_LIBRARY__ defined.  */
  42. #ifdef  __GNU_LIBRARY__
  43. #undef  alloca
  44. /* Don't include stdlib.h for non-GNU C libraries because some of them
  45.    contain conflicting prototypes for getopt.  */
  46. #include <stdlib.h>
  47. #else   /* Not GNU C library.  */
  48. #define __alloca        alloca
  49. #endif  /* GNU C library.  */
  50.  
  51. #if !__STDC__
  52. #define const
  53. #endif
  54.  
  55. /* If GETOPT_COMPAT is defined, `+' as well as `--' can introduce a
  56.    long-named option.  Because this is not POSIX.2 compliant, it is
  57.    being phased out.  */
  58. #define GETOPT_COMPAT
  59.  
  60. /* This version of `getopt' appears to the caller like standard Unix `getopt'
  61.    but it behaves differently for the user, since it allows the user
  62.    to intersperse the options with the other arguments.
  63.  
  64.    As `getopt' works, it permutes the elements of ARGV so that,
  65.    when it is done, all the options precede everything else.  Thus
  66.    all application programs are extended to handle flexible argument order.
  67.  
  68.    Setting the environment variable POSIXLY_CORRECT disables permutation.
  69.    Then the behavior is completely standard.
  70.  
  71.    GNU application programs can use a third alternative mode in which
  72.    they can distinguish the relative order of options and other arguments.  */
  73.  
  74. #include "getopt.h"
  75.  
  76. /* For communication from `getopt' to the caller.
  77.    When `getopt' finds an option that takes an argument,
  78.    the argument value is returned here.
  79.    Also, when `ordering' is RETURN_IN_ORDER,
  80.    each non-option ARGV-element is returned here.  */
  81.  
  82. char *optarg = 0;
  83.  
  84. /* Index in ARGV of the next element to be scanned.
  85.    This is used for communication to and from the caller
  86.    and for communication between successive calls to `getopt'.
  87.  
  88.    On entry to `getopt', zero means this is the first call; initialize.
  89.  
  90.    When `getopt' returns EOF, this is the index of the first of the
  91.    non-option elements that the caller should itself scan.
  92.  
  93.    Otherwise, `optind' communicates from one call to the next
  94.    how much of ARGV has been scanned so far.  */
  95.  
  96. int optind = 0;
  97.  
  98. /* The next char to be scanned in the option-element
  99.    in which the last option character we returned was found.
  100.    This allows us to pick up the scan where we left off.
  101.  
  102.    If this is zero, or a null string, it means resume the scan
  103.    by advancing to the next ARGV-element.  */
  104.  
  105. static char *nextchar;
  106.  
  107. /* Callers store zero here to inhibit the error message
  108.    for unrecognized options.  */
  109.  
  110. int opterr = 1;
  111.  
  112. /* Describe how to deal with options that follow non-option ARGV-elements.
  113.  
  114.    If the caller did not specify anything,
  115.    the default is REQUIRE_ORDER if the environment variable
  116.    POSIXLY_CORRECT is defined, PERMUTE otherwise.
  117.  
  118.    REQUIRE_ORDER means don't recognize them as options;
  119.    stop option processing when the first non-option is seen.
  120.    This is what Unix does.
  121.    This mode of operation is selected by either setting the environment
  122.    variable POSIXLY_CORRECT, or using `+' as the first character
  123.    of the list of option characters.
  124.  
  125.    PERMUTE is the default.  We permute the contents of ARGV as we scan,
  126.    so that eventually all the non-options are at the end.  This allows options
  127.    to be given in any order, even with programs that were not written to
  128.    expect this.
  129.  
  130.    RETURN_IN_ORDER is an option available to programs that were written
  131.    to expect options and other ARGV-elements in any order and that care about
  132.    the ordering of the two.  We describe each non-option ARGV-element
  133.    as if it were the argument of an option with character code 1.
  134.    Using `-' as the first character of the list of option characters
  135.    selects this mode of operation.
  136.  
  137.    The special argument `--' forces an end of option-scanning regardless
  138.    of the value of `ordering'.  In the case of RETURN_IN_ORDER, only
  139.    `--' can cause `getopt' to return EOF with `optind' != ARGC.  */
  140.  
  141. static enum
  142. {
  143.   REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER
  144. } ordering;
  145.  
  146. #ifdef  __GNU_LIBRARY__
  147. /* We want to avoid inclusion of string.h with non-GNU libraries
  148.    because there are many ways it can cause trouble.
  149.    On some systems, it contains special magic macros that don't work
  150.    in GCC.  */
  151. #include <string.h>
  152. #define my_index        strchr
  153. #define my_bcopy(src, dst, n)   memcpy ((dst), (src), (n))
  154. #else
  155.  
  156. /* Avoid depending on library functions or files
  157.    whose names are inconsistent.  */
  158.  
  159. char *getenv ();
  160.  
  161. static char *
  162. my_index (string, chr)
  163.      char *string;
  164.      int chr;
  165. {
  166.   while (*string)
  167.     {
  168.       if (*string == chr)
  169.         return string;
  170.       string++;
  171.     }
  172.   return 0;
  173. }
  174.  
  175. static void
  176. my_bcopy (from, to, size)
  177.      char *from, *to;
  178.      int size;
  179. {
  180.   int i;
  181.   for (i = 0; i < size; i++)
  182.     to[i] = from[i];
  183. }
  184. #endif                          /* GNU C library.  */
  185.  
  186. /* Handle permutation of arguments.  */
  187.  
  188. /* Describe the part of ARGV that contains non-options that have
  189.    been skipped.  `first_nonopt' is the index in ARGV of the first of them;
  190.    `last_nonopt' is the index after the last of them.  */
  191.  
  192. static int first_nonopt;
  193. static int last_nonopt;
  194.  
  195. /* Exchange two adjacent subsequences of ARGV.
  196.    One subsequence is elements [first_nonopt,last_nonopt)
  197.    which contains all the non-options that have been skipped so far.
  198.    The other is elements [last_nonopt,optind), which contains all
  199.    the options processed since those non-options were skipped.
  200.  
  201.    `first_nonopt' and `last_nonopt' are relocated so that they describe
  202.    the new indices of the non-options in ARGV after they are moved.  */
  203.  
  204. static void
  205. exchange (argv)
  206.      char **argv;
  207. {
  208.   int nonopts_size = (last_nonopt - first_nonopt) * sizeof (char *);
  209.   char **temp = (char **) __alloca (nonopts_size);
  210.  
  211.   /* Interchange the two blocks of data in ARGV.  */
  212.  
  213.   my_bcopy ((char *) &argv[first_nonopt], (char *) temp, nonopts_size);
  214.   my_bcopy ((char *) &argv[last_nonopt], (char *) &argv[first_nonopt],
  215.             (optind - last_nonopt) * sizeof (char *));
  216.   my_bcopy ((char *) temp,
  217.             (char *) &argv[first_nonopt + optind - last_nonopt],
  218.             nonopts_size);
  219.  
  220.   /* Update records for the slots the non-options now occupy.  */
  221.  
  222.   first_nonopt += (optind - last_nonopt);
  223.   last_nonopt = optind;
  224. }
  225.  
  226. /* Scan elements of ARGV (whose length is ARGC) for option characters
  227.    given in OPTSTRING.
  228.  
  229.    If an element of ARGV starts with '-', and is not exactly "-" or "--",
  230.    then it is an option element.  The characters of this element
  231.    (aside from the initial '-') are option characters.  If `getopt'
  232.    is called repeatedly, it returns successively each of the option characters
  233.    from each of the option elements.
  234.  
  235.    If `getopt' finds another option character, it returns that character,
  236.    updating `optind' and `nextchar' so that the next call to `getopt' can
  237.    resume the scan with the following option character or ARGV-element.
  238.  
  239.    If there are no more option characters, `getopt' returns `EOF'.
  240.    Then `optind' is the index in ARGV of the first ARGV-element
  241.    that is not an option.  (The ARGV-elements have been permuted
  242.    so that those that are not options now come last.)
  243.  
  244.    OPTSTRING is a string containing the legitimate option characters.
  245.    If an option character is seen that is not listed in OPTSTRING,
  246.    return '?' after printing an error message.  If you set `opterr' to
  247.    zero, the error message is suppressed but we still return '?'.
  248.  
  249.    If a char in OPTSTRING is followed by a colon, that means it wants an arg,
  250.    so the following text in the same ARGV-element, or the text of the following
  251.    ARGV-element, is returned in `optarg'.  Two colons mean an option that
  252.    wants an optional arg; if there is text in the current ARGV-element,
  253.    it is returned in `optarg', otherwise `optarg' is set to zero.
  254.  
  255.    If OPTSTRING starts with `-' or `+', it requests different methods of
  256.    handling the non-option ARGV-elements.
  257.    See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
  258.  
  259.    Long-named options begin with `--' instead of `-'.
  260.    Their names may be abbreviated as long as the abbreviation is unique
  261.    or is an exact match for some defined option.  If they have an
  262.    argument, it follows the option name in the same ARGV-element, separated
  263.    from the option name by a `=', or else the in next ARGV-element.
  264.    When `getopt' finds a long-named option, it returns 0 if that option's
  265.    `flag' field is nonzero, the value of the option's `val' field
  266.    if the `flag' field is zero.
  267.  
  268.    The elements of ARGV aren't really const, because we permute them.
  269.    But we pretend they're const in the prototype to be compatible
  270.    with other systems.
  271.  
  272.    LONGOPTS is a vector of `struct option' terminated by an
  273.    element containing a name which is zero.
  274.  
  275.    LONGIND returns the index in LONGOPT of the long-named option found.
  276.    It is only valid when a long-named option has been found by the most
  277.    recent call.
  278.  
  279.    If LONG_ONLY is nonzero, '-' as well as '--' can introduce
  280.    long-named options.  */
  281.  
  282. int
  283. _getopt_internal (argc, argv, optstring, longopts, longind, long_only)
  284.      int argc;
  285.      char *const *argv;
  286.      const char *optstring;
  287.      const struct option *longopts;
  288.      int *longind;
  289.      int long_only;
  290. {
  291.   int option_index;
  292.  
  293.   optarg = 0;
  294.  
  295.   /* Initialize the internal data when the first call is made.
  296.      Start processing options with ARGV-element 1 (since ARGV-element 0
  297.      is the program name); the sequence of previously skipped
  298.      non-option ARGV-elements is empty.  */
  299.  
  300.   if (optind == 0)
  301.     {
  302.       first_nonopt = last_nonopt = optind = 1;
  303.  
  304.       nextchar = NULL;
  305.  
  306.       /* Determine how to handle the ordering of options and nonoptions.  */
  307.  
  308.       if (optstring[0] == '-')
  309.         {
  310.           ordering = RETURN_IN_ORDER;
  311.           ++optstring;
  312.         }
  313.       else if (optstring[0] == '+')
  314.         {
  315.           ordering = REQUIRE_ORDER;
  316.           ++optstring;
  317.         }
  318.       else if (getenv ("POSIXLY_CORRECT") != NULL)
  319.         ordering = REQUIRE_ORDER;
  320.       else
  321.         ordering = PERMUTE;
  322.     }
  323.  
  324.   if (nextchar == NULL || *nextchar == '\0')
  325.     {
  326.       if (ordering == PERMUTE)
  327.         {
  328.           /* If we have just processed some options following some non-options,
  329.              exchange them so that the options come first.  */
  330.  
  331.           if (first_nonopt != last_nonopt && last_nonopt != optind)
  332.             exchange ((char **) argv);
  333.           else if (last_nonopt != optind)
  334.             first_nonopt = optind;
  335.  
  336.           /* Now skip any additional non-options
  337.              and extend the range of non-options previously skipped.  */
  338.  
  339.           while (optind < argc
  340.                  && (argv[optind][0] != '-' || argv[optind][1] == '\0')
  341. #ifdef GETOPT_COMPAT
  342.                  && (longopts == NULL
  343.                      || argv[optind][0] != '+' || argv[optind][1] == '\0')
  344. #endif                          /* GETOPT_COMPAT */
  345.                  )
  346.             optind++;
  347.           last_nonopt = optind;
  348.         }
  349.  
  350.       /* Special ARGV-element `--' means premature end of options.
  351.          Skip it like a null option,
  352.          then exchange with previous non-options as if it were an option,
  353.          then skip everything else like a non-option.  */
  354.  
  355.       if (optind != argc && !strcmp (argv[optind], "--"))
  356.         {
  357.           optind++;
  358.  
  359.           if (first_nonopt != last_nonopt && last_nonopt != optind)
  360.             exchange ((char **) argv);
  361.           else if (first_nonopt == last_nonopt)
  362.             first_nonopt = optind;
  363.           last_nonopt = argc;
  364.  
  365.           optind = argc;
  366.         }
  367.  
  368.       /* If we have done all the ARGV-elements, stop the scan
  369.          and back over any non-options that we skipped and permuted.  */
  370.  
  371.       if (optind == argc)
  372.         {
  373.           /* Set the next-arg-index to point at the non-options
  374.              that we previously skipped, so the caller will digest them.  */
  375.           if (first_nonopt != last_nonopt)
  376.             optind = first_nonopt;
  377.           return EOF;
  378.         }
  379.  
  380.       /* If we have come to a non-option and did not permute it,
  381.          either stop the scan or describe it to the caller and pass it by.  */
  382.  
  383.       if ((argv[optind][0] != '-' || argv[optind][1] == '\0')
  384. #ifdef GETOPT_COMPAT
  385.           && (longopts == NULL
  386.               || argv[optind][0] != '+' || argv[optind][1] == '\0')
  387. #endif                          /* GETOPT_COMPAT */
  388.           )
  389.         {
  390.           if (ordering == REQUIRE_ORDER)
  391.             return EOF;
  392.           optarg = argv[optind++];
  393.           return 1;
  394.         }
  395.  
  396.       /* We have found another option-ARGV-element.
  397.          Start decoding its characters.  */
  398.  
  399.       nextchar = (argv[optind] + 1
  400.                   + (longopts != NULL && argv[optind][1] == '-'));
  401.     }
  402.  
  403.   if (longopts != NULL
  404.       && ((argv[optind][0] == '-'
  405.            && (argv[optind][1] == '-' || long_only))
  406. #ifdef GETOPT_COMPAT
  407.           || argv[optind][0] == '+'
  408. #endif                          /* GETOPT_COMPAT */
  409.           ))
  410.     {
  411.       const struct option *p;
  412.       char *s = nextchar;
  413.       int exact = 0;
  414.       int ambig = 0;
  415.       const struct option *pfound = NULL;
  416.       int indfound;
  417.  
  418.       while (*s && *s != '=')
  419.         s++;
  420.  
  421.       /* Test all options for either exact match or abbreviated matches.  */
  422.       for (p = longopts, option_index = 0; p->name;
  423.            p++, option_index++)
  424.         if (!strncmp (p->name, nextchar, s - nextchar))
  425.           {
  426.             if (s - nextchar == strlen (p->name))
  427.               {
  428.                 /* Exact match found.  */
  429.                 pfound = p;
  430.                 indfound = option_index;
  431.                 exact = 1;
  432.                 break;
  433.               }
  434.             else if (pfound == NULL)
  435.               {
  436.                 /* First nonexact match found.  */
  437.                 pfound = p;
  438.                 indfound = option_index;
  439.               }
  440.             else
  441.               /* Second nonexact match found.  */
  442.               ambig = 1;
  443.           }
  444.  
  445.       if (ambig && !exact)
  446.         {
  447.           if (opterr)
  448.             fprintf (stderr, "%s: option `%s' is ambiguous\n",
  449.                      argv[0], argv[optind]);
  450.           nextchar += strlen (nextchar);
  451.           optind++;
  452.           return '?';
  453.         }
  454.  
  455.       if (pfound != NULL)
  456.         {
  457.           option_index = indfound;
  458.           optind++;
  459.           if (*s)
  460.             {
  461.               /* Don't test has_arg with >, because some C compilers don't
  462.                  allow it to be used on enums.  */
  463.               if (pfound->has_arg)
  464.                 optarg = s + 1;
  465.               else
  466.                 {
  467.                   if (opterr)
  468.                     {
  469.                       if (argv[optind - 1][1] == '-')
  470.                         /* --option */
  471.                         fprintf (stderr,
  472.                                  "%s: option `--%s' doesn't allow an argument\n",
  473.                                  argv[0], pfound->name);
  474.                       else
  475.                         /* +option or -option */
  476.                         fprintf (stderr,
  477.                              "%s: option `%c%s' doesn't allow an argument\n",
  478.                              argv[0], argv[optind - 1][0], pfound->name);
  479.                     }
  480.                   nextchar += strlen (nextchar);
  481.                   return '?';
  482.                 }
  483.             }
  484.           else if (pfound->has_arg == 1)
  485.             {
  486.               if (optind < argc)
  487.                 optarg = argv[optind++];
  488.               else
  489.                 {
  490.                   if (opterr)
  491.                     fprintf (stderr, "%s: option `%s' requires an argument\n",
  492.                              argv[0], argv[optind - 1]);
  493.                   nextchar += strlen (nextchar);
  494.                   return '?';
  495.                 }
  496.             }
  497.           nextchar += strlen (nextchar);
  498.           if (longind != NULL)
  499.             *longind = option_index;
  500.           if (pfound->flag)
  501.             {
  502.               *(pfound->flag) = pfound->val;
  503.               return 0;
  504.             }
  505.           return pfound->val;
  506.         }
  507.       /* Can't find it as a long option.  If this is not getopt_long_only,
  508.          or the option starts with '--' or is not a valid short
  509.          option, then it's an error.
  510.          Otherwise interpret it as a short option.  */
  511.       if (!long_only || argv[optind][1] == '-'
  512. #ifdef GETOPT_COMPAT
  513.           || argv[optind][0] == '+'
  514. #endif                          /* GETOPT_COMPAT */
  515.           || my_index (optstring, *nextchar) == NULL)
  516.         {
  517.           if (opterr)
  518.             {
  519.               if (argv[optind][1] == '-')
  520.                 /* --option */
  521.                 fprintf (stderr, "%s: unrecognized option `--%s'\n",
  522.                          argv[0], nextchar);
  523.               else
  524.                 /* +option or -option */
  525.                 fprintf (stderr, "%s: unrecognized option `%c%s'\n",
  526.                          argv[0], argv[optind][0], nextchar);
  527.             }
  528.           nextchar = (char *) "";
  529.           optind++;
  530.           return '?';
  531.         }
  532.     }
  533.  
  534.   /* Look at and handle the next option-character.  */
  535.  
  536.   {
  537.     char c = *nextchar++;
  538.     char *temp = my_index (optstring, c);
  539.  
  540.     /* Increment `optind' when we start to process its last character.  */
  541.     if (*nextchar == '\0')
  542.       ++optind;
  543.  
  544.     if (temp == NULL || c == ':')
  545.       {
  546.         if (opterr)
  547.           {
  548.             if (c < 040 || c >= 0177)
  549.               fprintf (stderr, "%s: unrecognized option, character code 0%o\n",
  550.                        argv[0], c);
  551.             else
  552.               fprintf (stderr, "%s: unrecognized option `-%c'\n", argv[0], c);
  553.           }
  554.         return '?';
  555.       }
  556.     if (temp[1] == ':')
  557.       {
  558.         if (temp[2] == ':')
  559.           {
  560.             /* This is an option that accepts an argument optionally.  */
  561.             if (*nextchar != '\0')
  562.               {
  563.                 optarg = nextchar;
  564.                 optind++;
  565.               }
  566.             else
  567.               optarg = 0;
  568.             nextchar = NULL;
  569.           }
  570.         else
  571.           {
  572.             /* This is an option that requires an argument.  */
  573.             if (*nextchar != '\0')
  574.               {
  575.                 optarg = nextchar;
  576.                 /* If we end this ARGV-element by taking the rest as an arg,
  577.                    we must advance to the next element now.  */
  578.                 optind++;
  579.               }
  580.             else if (optind == argc)
  581.               {
  582.                 if (opterr)
  583.                   fprintf (stderr, "%s: option `-%c' requires an argument\n",
  584.                            argv[0], c);
  585.                 c = '?';
  586.               }
  587.             else
  588.               /* We already incremented `optind' once;
  589.                  increment it again when taking next ARGV-elt as argument.  */
  590.               optarg = argv[optind++];
  591.             nextchar = NULL;
  592.           }
  593.       }
  594.     return c;
  595.   }
  596. }
  597.  
  598. int
  599. getopt (argc, argv, optstring)
  600.      int argc;
  601.      char *const *argv;
  602.      const char *optstring;
  603. {
  604.   return _getopt_internal (argc, argv, optstring,
  605.                            (const struct option *) 0,
  606.                            (int *) 0,
  607.                            0);
  608. }
  609.  
  610. #ifdef TEST
  611.  
  612. /* Compile with -DTEST to make an executable for use in testing
  613.    the above definition of `getopt'.  */
  614.  
  615. int
  616. main (argc, argv)
  617.      int argc;
  618.      char **argv;
  619. {
  620.   int c;
  621.   int digit_optind = 0;
  622.  
  623.   while (1)
  624.     {
  625.       int this_option_optind = optind ? optind : 1;
  626.  
  627.       c = getopt (argc, argv, "abc:d:0123456789");
  628.       if (c == EOF)
  629.         break;
  630.  
  631.       switch (c)
  632.         {
  633.         case '0':
  634.         case '1':
  635.         case '2':
  636.         case '3':
  637.         case '4':
  638.         case '5':
  639.         case '6':
  640.         case '7':
  641.         case '8':
  642.         case '9':
  643.           if (digit_optind != 0 && digit_optind != this_option_optind)
  644.             printf ("digits occur in two different argv-elements.\n");
  645.           digit_optind = this_option_optind;
  646.           printf ("option %c\n", c);
  647.           break;
  648.  
  649.         case 'a':
  650.           printf ("option a\n");
  651.           break;
  652.  
  653.         case 'b':
  654.           printf ("option b\n");
  655.           break;
  656.  
  657.         case 'c':
  658.           printf ("option c with value `%s'\n", optarg);
  659.           break;
  660.  
  661.         case '?':
  662.           break;
  663.  
  664.         default:
  665.           printf ("?? getopt returned character code 0%o ??\n", c);
  666.         }
  667.     }
  668.  
  669.   if (optind < argc)
  670.     {
  671.       printf ("non-option ARGV-elements: ");
  672.       while (optind < argc)
  673.         printf ("%s ", argv[optind++]);
  674.       printf ("\n");
  675.     }
  676.  
  677.   exit (0);
  678. }
  679.  
  680. #endif /* TEST */
  681.