home *** CD-ROM | disk | FTP | other *** search
/ The Fred Fish Collection 1.5 / ffcollection-1-5-1992-11.iso / ff_disks / 200-299 / ff295.lzh / GnuGrep / getopt.c < prev    next >
C/C++ Source or Header  |  1989-12-27  |  17KB  |  491 lines

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