home *** CD-ROM | disk | FTP | other *** search
/ Shareware 1 2 the Maxx / sw_1.zip / sw_1 / PROGRAM / SBDOS10.ZIP / GETOPT.C < prev    next >
Text File  |  1992-06-23  |  17KB  |  564 lines

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