home *** CD-ROM | disk | FTP | other *** search
/ Power Programmierung 2 / Power-Programmierung CD 2 (Tewi)(1994).iso / gnu / gnulib / ohlutil / getopt.c < prev    next >
Encoding:
C/C++ Source or Header  |  1990-08-24  |  17.0 KB  |  592 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.  * MS-DOS port (c) 1990 by Thorsten Ohl, td12@ddagsi3.bitnet
  20.  *
  21.  * To this port, the same copying conditions apply as to the
  22.  * original release.
  23.  *
  24.  * IMPORTANT:
  25.  * This file is not identical to the original GNU release!
  26.  * You should have received this code as patch to the official
  27.  * GNU release.
  28.  *
  29.  * MORE IMPORTANT:
  30.  * This port comes with ABSOLUTELY NO WARRANTY.
  31.  *
  32.  * $Header: e:/gnu/fileutil/RCS/getopt.c'v 1.3.0.2 90/06/29 00:46:45 tho Stable $
  33.  */
  34.  
  35. #ifdef __STDC__
  36. #define CONST const
  37. #else
  38. #define CONST
  39. #endif
  40.  
  41. /* This version of `getopt' appears to the caller like standard Unix `getopt'
  42.    but it behaves differently for the user, since it allows the user
  43.    to intersperse the options with the other arguments.
  44.  
  45.    As `getopt' works, it permutes the elements of `argv' so that,
  46.    when it is done, all the options precede everything else.  Thus
  47.    all application programs are extended to handle flexible argument order.
  48.  
  49.    Setting the environment variable _POSIX_OPTION_ORDER disables permutation.
  50.    Then the behavior is completely standard.
  51.  
  52.    GNU application programs can use a third alternative mode in which
  53.    they can distinguish the relative order of options and other arguments.  */
  54.  
  55. #include <stdio.h>
  56.  
  57. /* If compiled with GNU C, use the built-in alloca */
  58. #ifdef __GNUC__
  59. #define alloca __builtin_alloca
  60. #else /* not __GNUC__ */
  61. #ifdef sparc
  62. #include <alloca.h>
  63. #else
  64. #ifdef MSDOS
  65. #include <malloc.h>
  66. #else /* not MSDOS */
  67. char *alloca ();
  68. #endif /* not MSDOS */
  69. #endif
  70. #endif /* not __GNUC__ */
  71.  
  72. #ifdef MSDOS
  73. static void exchange (char **argv);
  74. extern int getopt (int, char **, const char *);
  75. #endif /* MSDOS */
  76.  
  77. #if defined(STDC_HEADERS) || defined(__GNU_LIBRARY__)
  78. #include <stdlib.h>
  79. #include <string.h>
  80. #define bcopy(s, d, n) memcpy ((d), (s), (n))
  81. #define index strchr
  82. #else
  83.  
  84. #ifdef USG
  85. #define bcopy(s, d, n) memcpy ((d), (s), (n))
  86. #define index strchr
  87. #endif
  88.  
  89. char *getenv ();
  90. char *index ();
  91. char *malloc ();
  92. #endif
  93.  
  94. /* For communication from `getopt' to the caller.
  95.    When `getopt' finds an option that takes an argument,
  96.    the argument value is returned here.
  97.    Also, when `ordering' is RETURN_IN_ORDER,
  98.    each non-option ARGV-element is returned here.  */
  99.  
  100. char *optarg = 0;
  101.  
  102. /* Index in ARGV of the next element to be scanned.
  103.    This is used for communication to and from the caller
  104.    and for communication between successive calls to `getopt'.
  105.  
  106.    On entry to `getopt', zero means this is the first call; initialize.
  107.  
  108.    When `getopt' returns EOF, this is the index of the first of the
  109.    non-option elements that the caller should itself scan.
  110.  
  111.    Otherwise, `optind' communicates from one call to the next
  112.    how much of ARGV has been scanned so far.  */
  113.  
  114. int optind = 0;
  115.  
  116. /* The next char to be scanned in the option-element
  117.    in which the last option character we returned was found.
  118.    This allows us to pick up the scan where we left off.
  119.  
  120.    If this is zero, or a null string, it means resume the scan
  121.    by advancing to the next ARGV-element.  */
  122.  
  123. static char *nextchar;
  124.  
  125. /* Callers store zero here to inhibit the error message
  126.    for unrecognized options.  */
  127.  
  128. int opterr = 1;
  129.  
  130. /* Describe how to deal with options that follow non-option ARGV-elements.
  131.  
  132.    If the caller did not specify anything,
  133.    the default is REQUIRE_ORDER if the environment variable
  134.    _POSIX_OPTION_ORDER is defined, PERMUTE otherwise.
  135.  
  136.    REQUIRE_ORDER means don't recognize them as options.
  137.    Stop option processing when the first non-option is seen.
  138.    This is what Unix does.
  139.  
  140.    PERMUTE is the default.  We permute the contents of ARGV as we scan,
  141.    so that eventually all the options are at the end.  This allows options
  142.    to be given in any order, even with programs that were not written to
  143.    expect this.
  144.  
  145.    RETURN_IN_ORDER is an option available to programs that were written
  146.    to expect options and other ARGV-elements in any order and that care about
  147.    the ordering of the two.  We describe each non-option ARGV-element
  148.    as if it were the argument of an option with character code one.
  149.    Using `-' as the first character of the list of option characters
  150.    requests this mode of operation.
  151.  
  152.    The special argument `--' forces an end of option-scanning regardless
  153.    of the value of `ordering'.  In the case of RETURN_IN_ORDER, only
  154.    `--' can cause `getopt' to return EOF with `optind' != ARGC.  */
  155.  
  156. static enum { REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER } ordering;
  157.  
  158. /* Describe the long-named options requested by the application.
  159.    _GETOPT_LONG_OPTIONS is a vector of `struct option' terminated by an
  160.    element containing a name which is zero.
  161.    The field `has_arg' is 1 if the option takes an argument, 
  162.    2 if it takes an optional argument.  */
  163.  
  164. struct option
  165. {
  166.   char *name;
  167.   int has_arg;
  168.   int *flag;
  169.   int val;
  170. };
  171.  
  172. CONST struct option *_getopt_long_options;
  173.  
  174. int _getopt_long_only = 0;
  175.  
  176. /* Index in _GETOPT_LONG_OPTIONS of the long-named option actually found.
  177.    Only valid when a long-named option was found. */
  178.  
  179. int option_index;
  180.  
  181. /* Handle permutation of arguments.  */
  182.  
  183. /* Describe the part of ARGV that contains non-options that have
  184.    been skipped.  `first_nonopt' is the index in ARGV of the first of them;
  185.    `last_nonopt' is the index after the last of them.  */
  186.  
  187. static int first_nonopt;
  188. static int last_nonopt;
  189.  
  190. /* Exchange two adjacent subsequences of ARGV.
  191.    One subsequence is elements [first_nonopt,last_nonopt)
  192.     which contains all the non-options that have been skipped so far.
  193.    The other is elements [last_nonopt,optind), which contains all
  194.     the options processed since those non-options were skipped.
  195.  
  196.    `first_nonopt' and `last_nonopt' are relocated so that they describe
  197.     the new indices of the non-options in ARGV after they are moved.  */
  198.  
  199. static void
  200. exchange (argv)
  201.      char **argv;
  202. {
  203.   int nonopts_size
  204.     = (last_nonopt - first_nonopt) * sizeof (char *);
  205.   char **temp = (char **) alloca (nonopts_size);
  206.  
  207.   /* Interchange the two blocks of data in argv.  */
  208.  
  209.   bcopy (&argv[first_nonopt], temp, nonopts_size);
  210.   bcopy (&argv[last_nonopt], &argv[first_nonopt],
  211.      (optind - last_nonopt) * sizeof (char *));
  212.   bcopy (temp, &argv[first_nonopt + optind - last_nonopt],
  213.      nonopts_size);
  214.  
  215.   /* Update records for the slots the non-options now occupy.  */
  216.  
  217.   first_nonopt += (optind - last_nonopt);
  218.   last_nonopt = optind;
  219. }
  220.  
  221. /* Scan elements of ARGV (whose length is ARGC) for option characters
  222.    given in OPTSTRING.
  223.  
  224.    If an element of ARGV starts with '-', and is not exactly "-" or "--",
  225.    then it is an option element.  The characters of this element
  226.    (aside from the initial '-') are option characters.  If `getopt'
  227.    is called repeatedly, it returns successively each of the option characters
  228.    from each of the option elements.
  229.  
  230.    If `getopt' finds another option character, it returns that character,
  231.    updating `optind' and `nextchar' so that the next call to `getopt' can
  232.    resume the scan with the following option character or ARGV-element.
  233.  
  234.    If there are no more option characters, `getopt' returns `EOF'.
  235.    Then `optind' is the index in ARGV of the first ARGV-element
  236.    that is not an option.  (The ARGV-elements have been permuted
  237.    so that those that are not options now come last.)
  238.  
  239.    OPTSTRING is a string containing the legitimate option characters.
  240.    If an option character is seen that is not listed in OPTSTRING,
  241.    return '?' after printing an error message.  If you set `opterr' to
  242.    zero, the error message is suppressed but we still return '?'.
  243.  
  244.    If a char in OPTSTRING is followed by a colon, that means it wants an arg,
  245.    so the following text in the same ARGV-element, or the text of the following
  246.    ARGV-element, is returned in `optarg'.  Two colons mean an option that
  247.    wants an optional arg; if there is text in the current ARGV-element,
  248.    it is returned in `optarg', otherwise `optarg' is set to zero.
  249.  
  250.    If OPTSTRING starts with `-', it requests a different method of handling the
  251.    non-option ARGV-elements.  See the comments about RETURN_IN_ORDER, above.
  252.  
  253.    Long-named options begin with `+' instead of `-'.
  254.    Their names may be abbreviated as long as the abbreviation is unique
  255.    or is an exact match for some defined option.  If they have an
  256.    argument, it follows the option name in the same ARGV-element, separated
  257.    from the option name by a `=', or else the in next ARGV-element.
  258.    `getopt' returns 0 when it finds a long-named option.  */
  259.  
  260. int
  261. getopt (argc, argv, optstring)
  262.      int argc;
  263.      char **argv;
  264.      CONST char *optstring;
  265. {
  266.   optarg = 0;
  267.  
  268.   /* Initialize the internal data when the first call is made.
  269.      Start processing options with ARGV-element 1 (since ARGV-element 0
  270.      is the program name); the sequence of previously skipped
  271.      non-option ARGV-elements is empty.  */
  272.  
  273.   if (optind == 0)
  274.     {
  275.       first_nonopt = last_nonopt = optind = 1;
  276.  
  277.       nextchar = 0;
  278.  
  279.       /* Determine how to handle the ordering of options and nonoptions.  */
  280.  
  281.       if (optstring[0] == '-')
  282.     ordering = RETURN_IN_ORDER;
  283.       else if (getenv ("_POSIX_OPTION_ORDER") != 0)
  284.     ordering = REQUIRE_ORDER;
  285.       else
  286.     ordering = PERMUTE;
  287.     }
  288.  
  289.   if (nextchar == 0 || *nextchar == 0)
  290.     {
  291.       if (ordering == PERMUTE)
  292.     {
  293.       /* If we have just processed some options following some non-options,
  294.          exchange them so that the options come first.  */
  295.  
  296.       if (first_nonopt != last_nonopt && last_nonopt != optind)
  297.         exchange (argv);
  298.       else if (last_nonopt != optind)
  299.         first_nonopt = optind;
  300.  
  301.       /* Now skip any additional non-options
  302.          and extend the range of non-options previously skipped.  */
  303.  
  304.       while (optind < argc
  305.          && (argv[optind][0] != '-'
  306.              || argv[optind][1] == 0)
  307.          && (_getopt_long_options == 0
  308.              || argv[optind][0] != '+'
  309.              || argv[optind][1] == 0))
  310.         optind++;
  311.       last_nonopt = optind;
  312.     }
  313.  
  314.       /* Special ARGV-element `--' means premature end of options.
  315.      Skip it like a null option,
  316.      then exchange with previous non-options as if it were an option,
  317.      then skip everything else like a non-option.  */
  318.  
  319.       if (optind != argc && !strcmp (argv[optind], "--"))
  320.     {
  321.       optind++;
  322.  
  323.       if (first_nonopt != last_nonopt && last_nonopt != optind)
  324.         exchange (argv);
  325.       else if (first_nonopt == last_nonopt)
  326.         first_nonopt = optind;
  327.       last_nonopt = argc;
  328.  
  329.       optind = argc;
  330.     }
  331.  
  332.       /* If we have done all the ARGV-elements, stop the scan
  333.      and back over any non-options that we skipped and permuted.  */
  334.  
  335.       if (optind == argc)
  336.     {
  337.       /* Set the next-arg-index to point at the non-options
  338.          that we previously skipped, so the caller will digest them.  */
  339.       if (first_nonopt != last_nonopt)
  340.         optind = first_nonopt;
  341.       return EOF;
  342.     }
  343.      
  344.       /* If we have come to a non-option and did not permute it,
  345.      either stop the scan or describe it to the caller and pass it by.  */
  346.  
  347.       if ((argv[optind][0] != '-' || argv[optind][1] == 0)
  348.       && (_getopt_long_options == 0
  349.           || argv[optind][0] != '+' || argv[optind][1] == 0))
  350.     {
  351.       if (ordering == REQUIRE_ORDER)
  352.         return EOF;
  353.       optarg = argv[optind++];
  354.       return 1;
  355.     }
  356.  
  357.       /* We have found another option-ARGV-element.
  358.      Start decoding its characters.  */
  359.  
  360.       nextchar = argv[optind] + 1;
  361.     }
  362.  
  363.   if (_getopt_long_options != 0
  364.       && (argv[optind][0] == '+'
  365.       || (_getopt_long_only && argv[optind][0] == '-'))
  366.       )
  367.     {
  368.       CONST struct option *p;
  369.       char *s = nextchar;
  370.       int exact = 0;
  371.       int ambig = 0;
  372.       CONST struct option *pfound = 0;
  373.       int indfound;
  374.  
  375.       while (*s && *s != '=') s++;
  376.  
  377.       /* Test all options for either exact match or abbreviated matches.  */
  378.       for (p = _getopt_long_options, option_index = 0; p->name; 
  379.        p++, option_index++)
  380.     if (!strncmp (p->name, nextchar, s - nextchar))
  381.       {
  382.         if (s - nextchar == strlen (p->name))
  383.           {
  384.         /* Exact match found.  */
  385.         pfound = p;
  386.         indfound = option_index;
  387.         exact = 1;
  388.         break;
  389.           }
  390.         else if (pfound == 0)
  391.           {
  392.         /* First nonexact match found.  */
  393.         pfound = p;
  394.         indfound = option_index;
  395.           }
  396.         else
  397.           /* Second nonexact match found.  */
  398.           ambig = 1;
  399.       }
  400.  
  401.       if (ambig && !exact)
  402.     {
  403.       fprintf (stderr, "%s: option `%s' is ambiguous\n",
  404.            argv[0], argv[optind]);
  405.       nextchar += strlen (nextchar);               
  406.       return '?';
  407.     }
  408.  
  409.       if (pfound != 0)
  410.     {
  411.       option_index = indfound;
  412.       optind++;
  413.       if (*s)
  414.         {
  415.           if (pfound->has_arg > 0)
  416.         optarg = s + 1;
  417.           else
  418.         {
  419.           fprintf (stderr,
  420.                "%s: option `%c%s' doesn't allow an argument\n",
  421.                argv[0], argv[optind - 1][0], pfound->name);
  422.           nextchar += strlen (nextchar);               
  423.           return '?';
  424.         }
  425.         }
  426.       else if (pfound->has_arg == 1)
  427.         {
  428.           if (optind < argc)
  429.         optarg = argv[optind++];
  430.           else
  431.         {
  432.           fprintf (stderr, "%s: option `%s' requires an argument\n",
  433.                argv[0], argv[optind - 1]);
  434.           nextchar += strlen (nextchar);           
  435.           return '?';
  436.         }
  437.         }
  438.       nextchar += strlen (nextchar);
  439.       if (pfound->flag)
  440.         *(pfound->flag) = pfound->val;
  441.       return 0;
  442.     }
  443.       /* Can't find it as a long option.  If this is getopt_long_only,
  444.      and the option starts with '-' and is a valid short
  445.      option, then interpret it as a short option.  Otherwise it's
  446.      an error.  */
  447.       if (_getopt_long_only == 0 || argv[optind][0] == '+' ||
  448.       index (optstring, *nextchar) == 0)
  449.     {
  450.       if (opterr != 0)
  451.         fprintf (stderr, "%s: unrecognized option `%c%s'\n",
  452.              argv[0], argv[optind][0], nextchar);
  453.       nextchar += strlen (nextchar);           
  454.       return '?';
  455.     }
  456.     }
  457.  
  458.   /* Look at and handle the next option-character.  */
  459.  
  460.   {
  461.     char c = *nextchar++;
  462.     char *temp = index (optstring, c);
  463.  
  464.     /* Increment `optind' when we start to process its last character.  */
  465.     if (*nextchar == 0)
  466.       optind++;
  467.  
  468.     if (temp == 0 || c == ':')
  469.       {
  470.     if (opterr != 0)
  471.       {
  472.         if (c < 040 || c >= 0177)
  473.           fprintf (stderr, "%s: unrecognized option, character code 0%o\n",
  474.                argv[0], c);
  475.         else
  476.           fprintf (stderr, "%s: unrecognized option `-%c'\n",
  477.                argv[0], c);
  478.       }
  479.     return '?';
  480.       }
  481.     if (temp[1] == ':')
  482.       {
  483.     if (temp[2] == ':')
  484.       {
  485.         /* This is an option that accepts an argument optionally.  */
  486.         if (*nextchar != 0)
  487.           {
  488.             optarg = nextchar;
  489.         optind++;
  490.           }
  491.         else
  492.           optarg = 0;
  493.         nextchar = 0;
  494.       }
  495.     else
  496.       {
  497.         /* This is an option that requires an argument.  */
  498.         if (*nextchar != 0)
  499.           {
  500.         optarg = nextchar;
  501.         /* If we end this ARGV-element by taking the rest as an arg,
  502.            we must advance to the next element now.  */
  503.         optind++;
  504.           }
  505.         else if (optind == argc)
  506.           {
  507.         if (opterr != 0)
  508.           fprintf (stderr, "%s: option `-%c' requires an argument\n",
  509.                argv[0], c);
  510.         c = '?';
  511.           }
  512.         else
  513.           /* We already incremented `optind' once;
  514.          increment it again when taking next ARGV-elt as argument.  */
  515.           optarg = argv[optind++];
  516.         nextchar = 0;
  517.       }
  518.       }
  519.     return c;
  520.   }
  521. }
  522.  
  523. #ifdef TEST
  524.  
  525. /* Compile with -DTEST to make an executable for use in testing
  526.    the above definition of `getopt'.  */
  527.  
  528. int
  529. main (argc, argv)
  530.      int argc;
  531.      char **argv;
  532. {
  533.   char c;
  534.   int digit_optind = 0;
  535.  
  536.   while (1)
  537.     {
  538.       int this_option_optind = optind;
  539.       if ((c = getopt (argc, argv, "abc:d:0123456789")) == EOF)
  540.     break;
  541.  
  542.       switch (c)
  543.     {
  544.     case '0':
  545.     case '1':
  546.     case '2':
  547.     case '3':
  548.     case '4':
  549.     case '5':
  550.     case '6':
  551.     case '7':
  552.     case '8':
  553.     case '9':
  554.       if (digit_optind != 0 && digit_optind != this_option_optind)
  555.         printf ("digits occur in two different argv-elements.\n");
  556.       digit_optind = this_option_optind;
  557.       printf ("option %c\n", c);
  558.       break;
  559.  
  560.     case 'a':
  561.       printf ("option a\n");
  562.       break;
  563.  
  564.     case 'b':
  565.       printf ("option b\n");
  566.       break;
  567.  
  568.     case 'c':
  569.       printf ("option c with value `%s'\n", optarg);
  570.       break;
  571.  
  572.     case '?':
  573.       break;
  574.  
  575.     default:
  576.       printf ("?? getopt returned character code 0%o ??\n", c);
  577.     }
  578.     }
  579.  
  580.   if (optind < argc)
  581.     {
  582.       printf ("non-option ARGV-elements: ");
  583.       while (optind < argc)
  584.     printf ("%s ", argv[optind++]);
  585.       printf ("\n");
  586.     }
  587.  
  588.   return 0;
  589. }
  590.  
  591. #endif /* TEST */
  592.