home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / rcs567s.zip / diff16 / getopt.c < prev    next >
C/C++ Source or Header  |  1994-06-25  |  18KB  |  611 lines

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