home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 11 Util / 11-Util.zip / DIFFPT.ZIP / GETOPT.C < prev    next >
C/C++ Source or Header  |  1991-07-01  |  17KB  |  605 lines

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