home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 6 File / 06-File.zip / FBE11.ZIP / GETOPT.C < prev    next >
C/C++ Source or Header  |  1990-09-06  |  18KB  |  506 lines

  1. //    ===================================================================
  2. //
  3. //        Modified for Microsoft C 5.1 by Dave Peckham, September 5, 1990
  4. //            - Added "#ifdef MSC"
  5. //            - Converted K&R function definitions to ANSI
  6. //            - Created getopt.h to hold new ANSI function prototypes
  7. //
  8. //    ===================================================================
  9.  
  10. #include "getopt.h"
  11.  
  12. /* Getopt for GNU.
  13.    Copyright (C) 1987 Free Software Foundation, Inc.
  14.  
  15.  
  16.  
  17.                NO WARRANTY
  18.  
  19.   BECAUSE THIS PROGRAM IS LICENSED FREE OF CHARGE, WE PROVIDE ABSOLUTELY
  20. NO WARRANTY, TO THE EXTENT PERMITTED BY APPLICABLE STATE LAW.  EXCEPT
  21. WHEN OTHERWISE STATED IN WRITING, FREE SOFTWARE FOUNDATION, INC,
  22. RICHARD M. STALLMAN AND/OR OTHER PARTIES PROVIDE THIS PROGRAM "AS IS"
  23. WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
  24. BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  25. FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY
  26. AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE PROGRAM PROVE
  27. DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
  28. CORRECTION.
  29.  
  30.  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW WILL RICHARD M.
  31. STALLMAN, THE FREE SOFTWARE FOUNDATION, INC., AND/OR ANY OTHER PARTY
  32. WHO MAY MODIFY AND REDISTRIBUTE THIS PROGRAM AS PERMITTED BELOW, BE
  33. LIABLE TO YOU FOR DAMAGES, INCLUDING ANY LOST PROFITS, LOST MONIES, OR
  34. OTHER SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
  35. USE OR INABILITY TO USE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR
  36. DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY THIRD PARTIES OR
  37. A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS) THIS
  38. PROGRAM, EVEN IF YOU HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH
  39. DAMAGES, OR FOR ANY CLAIM BY ANY OTHER PARTY.
  40.  
  41.         GENERAL PUBLIC LICENSE TO COPY
  42.  
  43.   1. You may copy and distribute verbatim copies of this source file
  44. as you receive it, in any medium, provided that you conspicuously and
  45. appropriately publish on each copy a valid copyright notice "Copyright
  46.  (C) 1987 Free Software Foundation, Inc."; and include following the
  47. copyright notice a verbatim copy of the above disclaimer of warranty
  48. and of this License.  You may charge a distribution fee for the
  49. physical act of transferring a copy.
  50.  
  51.   2. You may modify your copy or copies of this source file or
  52. any portion of it, and copy and distribute such modifications under
  53. the terms of Paragraph 1 above, provided that you also do the following:
  54.  
  55.     a) cause the modified files to carry prominent notices stating
  56.     that you changed the files and the date of any change; and
  57.  
  58.     b) cause the whole of any work that you distribute or publish,
  59.     that in whole or in part contains or is a derivative of this
  60.     program or any part thereof, to be licensed at no charge to all
  61.     third parties on terms identical to those contained in this
  62.     License Agreement (except that you may choose to grant more
  63.     extensive warranty protection to third parties, at your option).
  64.  
  65.     c) You may charge a distribution fee for the physical act of
  66.     transferring a copy, and you may at your option offer warranty
  67.     protection in exchange for a fee.
  68.  
  69.   3. You may copy and distribute this program or any portion of it in
  70. compiled, executable or object code form under the terms of Paragraphs
  71. 1 and 2 above provided that you do the following:
  72.  
  73.     a) cause each such copy to be accompanied by the
  74.     corresponding machine-readable source code, which must
  75.     be distributed under the terms of Paragraphs 1 and 2 above; or,
  76.  
  77.     b) cause each such copy to be accompanied by a
  78.     written offer, with no time limit, to give any third party
  79.     free (except for a nominal shipping charge) a machine readable
  80.     copy of the corresponding source code, to be distributed
  81.     under the terms of Paragraphs 1 and 2 above; or,
  82.  
  83.     c) in the case of a recipient of this program in compiled, executable
  84.     or object code form (without the corresponding source code) you
  85.     shall cause copies you distribute to be accompanied by a copy
  86.     of the written offer of source code which you received along
  87.     with the copy you received.
  88.  
  89.   4. You may not copy, sublicense, distribute or transfer this program
  90. except as expressly provided under this License Agreement.  Any attempt
  91. otherwise to copy, sublicense, distribute or transfer this program is void and
  92. your rights to use the program under this License agreement shall be
  93. automatically terminated.  However, parties who have received computer
  94. software programs from you with this License Agreement will not have
  95. their licenses terminated so long as such parties remain in full compliance.
  96.  
  97.   5. If you wish to incorporate parts of this program into other free
  98. programs whose distribution conditions are different, write to the Free
  99. Software Foundation at 675 Mass Ave, Cambridge, MA 02139.  We have not yet
  100. worked out a simple rule that can be stated here, but we will often permit
  101. this.  We will be guided by the two goals of preserving the free status of
  102. all derivatives of our free software and of promoting the sharing and reuse of
  103. software.
  104.  
  105.  
  106. In other words, you are welcome to use, share and improve this program.
  107. You are forbidden to forbid anyone else to use, share and improve
  108. what you give them.   Help stamp out software-hoarding!  */
  109.  
  110. /* This version of `getopt' appears to the caller like standard Unix `getopt'
  111.    but it behaves differently for the user, since it allows the user
  112.    to intersperse the options with the other arguments.
  113.  
  114.    As `getopt' works, it permutes the elements of `argv' so that,
  115.    when it is done, all the options precede everything else.  Thus
  116.    all application programs are extended to handle flexible argument order.
  117.  
  118.    Setting the environment variable _POSIX_OPTION_ORDER disables permutation.
  119.    Then the behavior is completely standard.
  120.  
  121.    GNU application programs can use a third alternative mode in which
  122.    they can distinguish the relative order of options and other arguments.  */
  123.  
  124. #include <stdio.h>
  125.  
  126. #ifdef sparc
  127. #include <alloca.h>
  128. #endif
  129. #ifdef USG
  130. #define bcopy(s, d, l) memcpy((d), (s), (l))
  131. #endif
  132.  
  133. #ifdef MSC
  134. #include <string.h>
  135. #include <stdlib.h>
  136. #include <malloc.h>
  137. #define bcopy(s, d, l) memcpy((d), (s), (l))
  138. #define index strchr
  139. #endif
  140.  
  141. /* For communication from `getopt' to the caller.
  142.    When `getopt' finds an option that takes an argument,
  143.    the argument value is returned here.
  144.    Also, when `ordering' is RETURN_IN_ORDER,
  145.    each non-option ARGV-element is returned here.  */
  146.             
  147. char *optarg = 0;
  148.  
  149. /* Index in ARGV of the next element to be scanned.
  150.    This is used for communication to and from the caller
  151.    and for communication between successive calls to `getopt'.
  152.  
  153.    On entry to `getopt', zero means this is the first call; initialize.
  154.  
  155.    When `getopt' returns EOF, this is the index of the first of the
  156.    non-option elements that the caller should itself scan.
  157.  
  158.    Otherwise, `optind' communicates from one call to the next
  159.    how much of ARGV has been scanned so far.  */
  160.  
  161. int optind = 0;
  162.  
  163. /* The next char to be scanned in the option-element
  164.    in which the last option character we returned was found.
  165.    This allows us to pick up the scan where we left off.
  166.  
  167.    If this is zero, or a null string, it means resume the scan
  168.    by advancing to the next ARGV-element.  */
  169.  
  170. static char *nextchar;
  171.  
  172. /* Callers store zero here to inhibit the error message
  173.    for unrecognized options.  */
  174.  
  175. int opterr = 1;
  176.  
  177. /* Describe how to deal with options that follow non-option ARGV-elements.
  178.  
  179.    UNSPECIFIED means the caller did not specify anything;
  180.    the default is then REQUIRE_ORDER if the environment variable
  181.    _OPTIONS_FIRST is defined, PERMUTE otherwise.
  182.  
  183.    REQUIRE_ORDER means don't recognize them as options.
  184.    Stop option processing when the first non-option is seen.
  185.    This is what Unix does.
  186.  
  187.    PERMUTE is the default.  We permute the contents of `argv' as we scan,
  188.    so that eventually all the options are at the end.  This allows options
  189.    to be given in any order, even with programs that were not written to
  190.    expect this.
  191.  
  192.    RETURN_IN_ORDER is an option available to programs that were written
  193.    to expect options and other ARGV-elements in any order and that care about
  194.    the ordering of the two.  We describe each non-option ARGV-element
  195.    as if it were the argument of an option with character code zero.
  196.    Using `-' as the first character of the list of option characters
  197.    requests this mode of operation.
  198.  
  199.    The special argument `--' forces an end of option-scanning regardless
  200.    of the value of `ordering'.  In the case of RETURN_IN_ORDER, only
  201.    `--' can cause `getopt' to return EOF with `optind' != ARGC.  */
  202.  
  203. static enum { REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER } ordering;
  204.  
  205. /* Handle permutation of arguments.  */
  206.  
  207. /* Describe the part of ARGV that contains non-options that have
  208.    been skipped.  `first_nonopt' is the index in ARGV of the first of them;
  209.    `last_nonopt' is the index after the last of them.  */
  210.  
  211. static int first_nonopt;
  212. static int last_nonopt;
  213.  
  214. /* Exchange two adjacent subsequences of ARGV.
  215.    One subsequence is elements [first_nonopt,last_nonopt)
  216.     which contains all the non-options that have been skipped so far.
  217.    The other is elements [last_nonopt,optind), which contains all
  218.     the options processed since those non-options were skipped.
  219.  
  220.    `first_nonopt' and `last_nonopt' are relocated so that they describe
  221.     the new indices of the non-options in ARGV after they are moved.  */
  222.  
  223. static void
  224. exchange (char **argv)
  225. {
  226.   int nonopts_size
  227.     = (last_nonopt - first_nonopt) * sizeof (char *);
  228.   char **temp = (char **) alloca (nonopts_size);
  229.  
  230.   /* Interchange the two blocks of data in argv.  */
  231.  
  232.   bcopy (&argv[first_nonopt], temp, nonopts_size);
  233.   bcopy (&argv[last_nonopt], &argv[first_nonopt],
  234.      (optind - last_nonopt) * sizeof (char *));
  235.   bcopy (temp, &argv[first_nonopt + optind - last_nonopt],
  236.      nonopts_size);
  237.  
  238.   /* Update records for the slots the non-options now occupy.  */
  239.  
  240.   first_nonopt += (optind - last_nonopt);
  241.   last_nonopt = optind;
  242. }
  243.  
  244. /* Scan elements of ARGV (whose length is ARGC) for option characters
  245.    given in OPTSTRING.
  246.  
  247.    If an element of ARGV starts with '-', and is not exactly "-" or "--",
  248.    then it is an option element.  The characters of this element
  249.    (aside from the initial '-') are option characters.  If `getopt'
  250.    is called repeatedly, it returns successively each of theoption characters
  251.    from each of the option elements.
  252.  
  253.    If `getopt' finds another option character, it returns that character,
  254.    updating `optind' and `nextchar' so that the next call to `getopt' can
  255.    resume the scan with the following option character or ARGV-element.
  256.  
  257.    If there are no more option characters, `getopt' returns `EOF'.
  258.    Then `optind' is the index in ARGV of the first ARGV-element
  259.    that is not an option.  (The ARGV-elements have been permuted
  260.    so that those that are not options now come last.)
  261.  
  262.    OPTSTRING is a string containing the legitimate option characters.
  263.    A colon in OPTSTRING means that the previous character is an option
  264.    that wants an argument.  The argument is taken from the rest of the
  265.    current ARGV-element, or from the following ARGV-element,
  266.    and returned in `optarg'.
  267.  
  268.    If an option character is seen that is not listed in OPTSTRING,
  269.    return '?' after printing an error message.  If you set `opterr' to
  270.    zero, the error message is suppressed but we still return '?'.
  271.  
  272.    If a char in OPTSTRING is followed by a colon, that means it wants an arg,
  273.    so the following text in the same ARGV-element, or the text of the following
  274.    ARGV-element, is returned in `optarg.  Two colons mean an option that
  275.    wants an optional arg; if there is text in the current ARGV-element,
  276.    it is returned in `optarg'.
  277.  
  278.    If OPTSTRING starts with `-', it requests a different method of handling the
  279.    non-option ARGV-elements.  See the comments about RETURN_IN_ORDER, above.  */
  280.  
  281. int
  282. getopt (int argc, char **argv, char *optstring)
  283. {
  284.   /* Initialize the internal data when the first call is made.
  285.      Start processing options with ARGV-element 1 (since ARGV-element 0
  286.      is the program name); the sequence of previously skipped
  287.      non-option ARGV-elements is empty.  */
  288.  
  289.   if (optind == 0)
  290.     {
  291.       first_nonopt = last_nonopt = optind = 1;
  292.  
  293.       nextchar = 0;
  294.  
  295.       /* Determine how to handle the ordering of options and nonoptions.  */
  296.  
  297.       if (optstring[0] == '-')
  298.     ordering = RETURN_IN_ORDER;
  299.       else if (getenv ("_POSIX_OPTION_ORDER") != 0)
  300.     ordering = REQUIRE_ORDER;
  301.       else
  302.     ordering = PERMUTE;
  303.     }
  304.  
  305.   if (nextchar == 0 || *nextchar == 0)
  306.     {
  307.       if (ordering == PERMUTE)
  308.     {
  309.       /* If we have just processed some options following some non-options,
  310.          exchange them so that the options come first.  */
  311.  
  312.       if (first_nonopt != last_nonopt && last_nonopt != optind)
  313.         exchange (argv);
  314.       else if (last_nonopt != optind)
  315.         first_nonopt = optind;
  316.  
  317.       /* Now skip any additional non-options
  318.          and extend the range of non-options previously skipped.  */
  319.  
  320.       while (optind < argc
  321.          && (argv[optind][0] != '-'
  322.              || argv[optind][1] == 0))
  323.         optind++;
  324.       last_nonopt = optind;
  325.     }
  326.  
  327.       /* Special ARGV-element `--' means premature end of options.
  328.      Skip it like a null option,
  329.      then exchange with previous non-options as if it were an option,
  330.      then skip everything else like a non-option.  */
  331.  
  332.       if (optind != argc && !strcmp (argv[optind], "--"))
  333.     {
  334.       optind++;
  335.  
  336.       if (first_nonopt != last_nonopt && last_nonopt != optind)
  337.         exchange (argv);
  338.       else if (first_nonopt == last_nonopt)
  339.         first_nonopt = optind;
  340.       last_nonopt = argc;
  341.  
  342.       optind = argc;
  343.     }
  344.  
  345.       /* If we have done all the ARGV-elements, stop the scan
  346.      and back over any non-options that we skipped and permuted.  */
  347.  
  348.       if (optind == argc)
  349.     {
  350.       /* Set the next-arg-index to point at the non-options
  351.          that we previously skipped, so the caller will digest them.  */
  352.       if (first_nonopt != last_nonopt)
  353.         optind = first_nonopt;
  354.       return EOF;
  355.     }
  356.      
  357.       /* If we have come to a non-option and did not permute it,
  358.      either stop the scan or describe it to the caller and pass it by.  */
  359.  
  360.       if (argv[optind][0] != '-' || argv[optind][1] == 0)
  361.     {
  362.       if (ordering == REQUIRE_ORDER)
  363.         return EOF;
  364.       optarg = argv[optind++];
  365.       return 0;
  366.     }
  367.  
  368.       /* We have found another option-ARGV-element.
  369.      Start decoding its characters.  */
  370.  
  371.       nextchar = argv[optind] + 1;
  372.     }
  373.  
  374.   /* Look at and handle the next option-character.  */
  375.  
  376.   {
  377.     char c = *nextchar++;
  378.     char *temp = (char *) index (optstring, c);
  379.  
  380.     /* Increment `optind' when we start to process its last character.  */
  381.     if (*nextchar == 0)
  382.       optind++;
  383.  
  384.     if (temp == 0 || c == ':')
  385.       {
  386.     if (opterr != 0)
  387.       {
  388.         if (c < 040 || c >= 0177)
  389.           fprintf (stderr, "%s: unrecognized option, character code 0%o\n",
  390.                argv[0], c);
  391.         else
  392.           fprintf (stderr, "%s: unrecognized option `-%c'\n",
  393.                argv[0], c);
  394.       }
  395.     return '?';
  396.       }
  397.     if (temp[1] == ':')
  398.       {
  399.     if (temp[2] == ':')
  400.       {
  401.         /* This is an option that accepts an argument optionally.  */
  402.         if (*nextchar != 0)
  403.           {
  404.             optarg = nextchar;
  405.         optind++;
  406.           }
  407.         else
  408.           optarg = 0;
  409.         nextchar = 0;
  410.       }
  411.     else
  412.       {
  413.         /* This is an option that requires an argument.  */
  414.         if (*nextchar != 0)
  415.           {
  416.         optarg = nextchar;
  417.         /* If we end this ARGV-element by taking the rest as an arg,
  418.            we must advance to the next element now.  */
  419.         optind++;
  420.           }
  421.         else if (optind == argc)
  422.           {
  423.         if (opterr != 0)
  424.           fprintf (stderr, "%s: no argument for `-%c' option\n",
  425.                argv[0], c);
  426.         c = '?';
  427.           }
  428.         else
  429.           /* We already incremented `optind' once;
  430.          increment it again when taking next ARGV-elt as argument.  */
  431.           optarg = argv[optind++];
  432.         nextchar = 0;
  433.       }
  434.       }
  435.     return c;
  436.   }
  437. }
  438.  
  439. #ifdef TEST
  440.  
  441. /* Compile with -DTEST to make an executable for use in testing
  442.    the above definition of `getopt'.  */
  443.  
  444. int
  445. main (int argc, char **argv)
  446. {
  447.   char c;
  448.   int digit_optind = 0;
  449.  
  450.   while (1)
  451.     {
  452.       int this_option_optind = optind;
  453.       if ((c = getopt (argc, argv, "ab::c:d:0123456789")) == EOF)
  454.     break;
  455.  
  456.       switch (c)
  457.     {
  458.     case '0':
  459.     case '1':
  460.     case '2':
  461.     case '3':
  462.     case '4':
  463.     case '5':
  464.     case '6':
  465.     case '7':
  466.     case '8':
  467.     case '9':
  468.       if (digit_optind != 0 && digit_optind != this_option_optind)
  469.         printf ("digits occur in two different argv-elements.\n");
  470.       digit_optind = this_option_optind;
  471.       printf ("option %c\n", c);
  472.       break;
  473.  
  474.     case 'a':
  475.       printf ("option a\n");
  476.       break;
  477.  
  478.     case 'b':
  479.       printf ("option b with value `%s'\n", optarg);
  480.       break;
  481.  
  482.     case 'c':
  483.       printf ("option c with value `%s'\n", optarg);
  484.       break;
  485.  
  486.     case '?':
  487.       break;
  488.  
  489.     default:
  490.       printf ("?? getopt returned character code 0%o ??\n", c);
  491.     }
  492.     }
  493.  
  494.   if (optind < argc)
  495.     {
  496.       printf ("non-option ARGV-elements: ");
  497.       while (optind < argc)
  498.     printf ("%s ", argv[optind++]);
  499.       printf ("\n");
  500.     }
  501.  
  502.   return 0;
  503. }
  504.  
  505. #endif /* TEST */
  506.