home *** CD-ROM | disk | FTP | other *** search
/ ARM Club 3 / TheARMClub_PDCD3.iso / hensa / textprocess / grep_2 / release / c / getopt < prev    next >
Text File  |  1991-06-10  |  18KB  |  493 lines

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