home *** CD-ROM | disk | FTP | other *** search
/ Club Amiga de Montreal - CAM / CAM_CD_1.iso / files / 419b.lha / GNU_Awk_v2.10_Beta / getopt.c < prev    next >
C/C++ Source or Header  |  1990-10-01  |  13KB  |  418 lines

  1. /* Getopt for GNU.
  2.    Copyright (C) 1987, 1989 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 1, 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.  
  19.  
  20. /* This version of `getopt' appears to the caller like standard Unix `getopt'
  21.    but it behaves differently for the user, since it allows the user
  22.    to intersperse the options with the other arguments.
  23.  
  24.    As `getopt' works, it permutes the elements of `argv' so that,
  25.    when it is done, all the options precede everything else.  Thus
  26.    all application programs are extended to handle flexible argument order.
  27.  
  28.    Setting the environment variable _POSIX_OPTION_ORDER disables permutation.
  29.    Then the behavior is completely standard.
  30.  
  31.    GNU application programs can use a third alternative mode in which
  32.    they can distinguish the relative order of options and other arguments.  */
  33.  
  34. #include <stdio.h>
  35.  
  36. #ifdef sparc
  37. #include <alloca.h>
  38. #endif
  39. #if defined(USG) || defined(MSDOS)
  40. extern char *alloca();
  41. extern char *strchr();
  42. #define index    strchr
  43. #define bcopy(s, d, l) memcpy((d), (s), (l))
  44. #endif
  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.    UNSPECIFIED means the caller did not specify anything;
  85.    the default is then REQUIRE_ORDER if the environment variable
  86.    _OPTIONS_FIRST 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.  
  92.    PERMUTE is the default.  We permute the contents of `argv' as we scan,
  93.    so that eventually all the options are at the end.  This allows options
  94.    to be given in any order, even with programs that were not written to
  95.    expect this.
  96.  
  97.    RETURN_IN_ORDER is an option available to programs that were written
  98.    to expect options and other ARGV-elements in any order and that care about
  99.    the ordering of the two.  We describe each non-option ARGV-element
  100.    as if it were the argument of an option with character code zero.
  101.    Using `-' as the first character of the list of option characters
  102.    requests this mode of operation.
  103.  
  104.    The special argument `--' forces an end of option-scanning regardless
  105.    of the value of `ordering'.  In the case of RETURN_IN_ORDER, only
  106.    `--' can cause `getopt' to return EOF with `optind' != ARGC.  */
  107.  
  108. static enum { REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER } ordering;
  109.  
  110. /* Handle permutation of arguments.  */
  111.  
  112. /* Describe the part of ARGV that contains non-options that have
  113.    been skipped.  `first_nonopt' is the index in ARGV of the first of them;
  114.    `last_nonopt' is the index after the last of them.  */
  115.  
  116. static int first_nonopt;
  117. static int last_nonopt;
  118.  
  119. /* Exchange two adjacent subsequences of ARGV.
  120.    One subsequence is elements [first_nonopt,last_nonopt)
  121.     which contains all the non-options that have been skipped so far.
  122.    The other is elements [last_nonopt,optind), which contains all
  123.     the options processed since those non-options were skipped.
  124.  
  125.    `first_nonopt' and `last_nonopt' are relocated so that they describe
  126.     the new indices of the non-options in ARGV after they are moved.  */
  127.  
  128. static void
  129. exchange (argv)
  130.      char **argv;
  131. {
  132.   int nonopts_size
  133.     = (last_nonopt - first_nonopt) * sizeof (char *);
  134.   char **temp = (char **) alloca (nonopts_size);
  135.  
  136.   /* Interchange the two blocks of data in argv.  */
  137.  
  138.   bcopy (&argv[first_nonopt], temp, nonopts_size);
  139.   bcopy (&argv[last_nonopt], &argv[first_nonopt],
  140.      (optind - last_nonopt) * sizeof (char *));
  141.   bcopy (temp, &argv[first_nonopt + optind - last_nonopt],
  142.      nonopts_size);
  143.  
  144.   /* Update records for the slots the non-options now occupy.  */
  145.  
  146.   first_nonopt += (optind - last_nonopt);
  147.   last_nonopt = optind;
  148. }
  149.  
  150. /* Scan elements of ARGV (whose length is ARGC) for option characters
  151.    given in OPTSTRING.
  152.  
  153.    If an element of ARGV starts with '-', and is not exactly "-" or "--",
  154.    then it is an option element.  The characters of this element
  155.    (aside from the initial '-') are option characters.  If `getopt'
  156.    is called repeatedly, it returns successively each of theoption characters
  157.    from each of the option elements.
  158.  
  159.    If `getopt' finds another option character, it returns that character,
  160.    updating `optind' and `nextchar' so that the next call to `getopt' can
  161.    resume the scan with the following option character or ARGV-element.
  162.  
  163.    If there are no more option characters, `getopt' returns `EOF'.
  164.    Then `optind' is the index in ARGV of the first ARGV-element
  165.    that is not an option.  (The ARGV-elements have been permuted
  166.    so that those that are not options now come last.)
  167.  
  168.    OPTSTRING is a string containing the legitimate option characters.
  169.    A colon in OPTSTRING means that the previous character is an option
  170.    that wants an argument.  The argument is taken from the rest of the
  171.    current ARGV-element, or from the following ARGV-element,
  172.    and returned in `optarg'.
  173.  
  174.    If an option character is seen that is not listed in OPTSTRING,
  175.    return '?' after printing an error message.  If you set `opterr' to
  176.    zero, the error message is suppressed but we still return '?'.
  177.  
  178.    If a char in OPTSTRING is followed by a colon, that means it wants an arg,
  179.    so the following text in the same ARGV-element, or the text of the following
  180.    ARGV-element, is returned in `optarg.  Two colons mean an option that
  181.    wants an optional arg; if there is text in the current ARGV-element,
  182.    it is returned in `optarg'.
  183.  
  184.    If OPTSTRING starts with `-', it requests a different method of handling the
  185.    non-option ARGV-elements.  See the comments about RETURN_IN_ORDER, above.  */
  186.  
  187. int
  188. getopt (argc, argv, optstring)
  189.      int argc;
  190.      char **argv;
  191.      char *optstring;
  192. {
  193.   /* Initialize the internal data when the first call is made.
  194.      Start processing options with ARGV-element 1 (since ARGV-element 0
  195.      is the program name); the sequence of previously skipped
  196.      non-option ARGV-elements is empty.  */
  197.  
  198.   if (optind == 0)
  199.     {
  200.       first_nonopt = last_nonopt = optind = 1;
  201.  
  202.       nextchar = 0;
  203.  
  204.       /* Determine how to handle the ordering of options and nonoptions.  */
  205.  
  206.       if (optstring[0] == '-')
  207.     ordering = RETURN_IN_ORDER;
  208.       else if (getenv ("_POSIX_OPTION_ORDER") != 0)
  209.     ordering = REQUIRE_ORDER;
  210.       else
  211.     ordering = PERMUTE;
  212.     }
  213.  
  214.   if (nextchar == 0 || *nextchar == 0)
  215.     {
  216.       if (ordering == PERMUTE)
  217.     {
  218.       /* If we have just processed some options following some non-options,
  219.          exchange them so that the options come first.  */
  220.  
  221.       if (first_nonopt != last_nonopt && last_nonopt != optind)
  222.         exchange (argv);
  223.       else if (last_nonopt != optind)
  224.         first_nonopt = optind;
  225.  
  226.       /* Now skip any additional non-options
  227.          and extend the range of non-options previously skipped.  */
  228.  
  229.       while (optind < argc
  230.          && (argv[optind][0] != '-'
  231.              || argv[optind][1] == 0))
  232.         optind++;
  233.       last_nonopt = optind;
  234.     }
  235.  
  236.       /* Special ARGV-element `--' means premature end of options.
  237.      Skip it like a null option,
  238.      then exchange with previous non-options as if it were an option,
  239.      then skip everything else like a non-option.  */
  240.  
  241.       if (optind != argc && !strcmp (argv[optind], "--"))
  242.     {
  243.       optind++;
  244.  
  245.       if (first_nonopt != last_nonopt && last_nonopt != optind)
  246.         exchange (argv);
  247.       else if (first_nonopt == last_nonopt)
  248.         first_nonopt = optind;
  249.       last_nonopt = argc;
  250.  
  251.       optind = argc;
  252.     }
  253.  
  254.       /* If we have done all the ARGV-elements, stop the scan
  255.      and back over any non-options that we skipped and permuted.  */
  256.  
  257.       if (optind == argc)
  258.     {
  259.       /* Set the next-arg-index to point at the non-options
  260.          that we previously skipped, so the caller will digest them.  */
  261.       if (first_nonopt != last_nonopt)
  262.         optind = first_nonopt;
  263.       return EOF;
  264.     }
  265.      
  266.       /* If we have come to a non-option and did not permute it,
  267.      either stop the scan or describe it to the caller and pass it by.  */
  268.  
  269.       if (argv[optind][0] != '-' || argv[optind][1] == 0)
  270.     {
  271.       if (ordering == REQUIRE_ORDER)
  272.         return EOF;
  273.       optarg = argv[optind++];
  274.       return 0;
  275.     }
  276.  
  277.       /* We have found another option-ARGV-element.
  278.      Start decoding its characters.  */
  279.  
  280.       nextchar = argv[optind] + 1;
  281.     }
  282.  
  283.   /* Look at and handle the next option-character.  */
  284.  
  285.   {
  286.     char c = *nextchar++;
  287.     char *temp = (char *) index (optstring, c);
  288.  
  289.     /* Increment `optind' when we start to process its last character.  */
  290.     if (*nextchar == 0)
  291.       optind++;
  292.  
  293.     if (temp == 0 || c == ':')
  294.       {
  295.     if (opterr != 0)
  296.       {
  297.         if (c < 040 || c >= 0177)
  298.           fprintf (stderr, "%s: unrecognized option, character code 0%o\n",
  299.                argv[0], c);
  300.         else
  301.           fprintf (stderr, "%s: unrecognized option `-%c'\n",
  302.                argv[0], c);
  303.       }
  304.     return '?';
  305.       }
  306.     if (temp[1] == ':')
  307.       {
  308.     if (temp[2] == ':')
  309.       {
  310.         /* This is an option that accepts an argument optionally.  */
  311.         if (*nextchar != 0)
  312.           {
  313.             optarg = nextchar;
  314.         optind++;
  315.           }
  316.         else
  317.           optarg = 0;
  318.         nextchar = 0;
  319.       }
  320.     else
  321.       {
  322.         /* This is an option that requires an argument.  */
  323.         if (*nextchar != 0)
  324.           {
  325.         optarg = nextchar;
  326.         /* If we end this ARGV-element by taking the rest as an arg,
  327.            we must advance to the next element now.  */
  328.         optind++;
  329.           }
  330.         else if (optind == argc)
  331.           {
  332.         if (opterr != 0)
  333.           fprintf (stderr, "%s: no argument for `-%c' option\n",
  334.                argv[0], c);
  335.         c = '?';
  336.           }
  337.         else
  338.           /* We already incremented `optind' once;
  339.          increment it again when taking next ARGV-elt as argument.  */
  340.           optarg = argv[optind++];
  341.         nextchar = 0;
  342.       }
  343.       }
  344.     return c;
  345.   }
  346. }
  347.  
  348. #ifdef TEST
  349.  
  350. /* Compile with -DTEST to make an executable for use in testing
  351.    the above definition of `getopt'.  */
  352.  
  353. int
  354. main (argc, argv)
  355.      int argc;
  356.      char **argv;
  357. {
  358.   char c;
  359.   int digit_optind = 0;
  360.  
  361.   while (1)
  362.     {
  363.       int this_option_optind = optind;
  364.       if ((c = getopt (argc, argv, "abc:d:0123456789")) == EOF)
  365.     break;
  366.  
  367.       switch (c)
  368.     {
  369.     case '0':
  370.     case '1':
  371.     case '2':
  372.     case '3':
  373.     case '4':
  374.     case '5':
  375.     case '6':
  376.     case '7':
  377.     case '8':
  378.     case '9':
  379.       if (digit_optind != 0 && digit_optind != this_option_optind)
  380.         printf ("digits occur in two different argv-elements.\n");
  381.       digit_optind = this_option_optind;
  382.       printf ("option %c\n", c);
  383.       break;
  384.  
  385.     case 'a':
  386.       printf ("option a\n");
  387.       break;
  388.  
  389.     case 'b':
  390.       printf ("option b\n");
  391.       break;
  392.  
  393.     case 'c':
  394.       printf ("option c with value `%s'\n", optarg);
  395.       break;
  396.  
  397.     case '?':
  398.       break;
  399.  
  400.     default:
  401.       printf ("?? getopt returned character code 0%o ??\n", c);
  402.     }
  403.     }
  404.  
  405.   if (optind < argc)
  406.     {
  407.       printf ("non-option ARGV-elements: ");
  408.       while (optind < argc)
  409.     printf ("%s ", argv[optind++]);
  410.       printf ("\n");
  411.     }
  412.  
  413.   return 0;
  414. }
  415.  
  416. #endif /* TEST */
  417.  
  418.