home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 January / usenetsourcesnewsgroupsinfomagicjanuary1994.iso / sources / unix / volume20 / reactivekbd / part02 / getopt.c next >
Encoding:
C/C++ Source or Header  |  1989-10-16  |  15.9 KB  |  453 lines

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