2 NOTE: getopt is now part of the C library, so if you don't know what
3 "Keep this file name-space clean" means, talk to roland@gnu.ai.mit.edu
6 Copyright (C) 1987, 88, 89, 90, 91, 1992 Free Software Foundation, Inc.
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2, or (at your option)
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */
22 /* AIX requires this to be the first thing in the file. */
24 #define alloca __builtin_alloca
25 #else /* not __GNUC__ */
26 #if defined(sparc) && !defined(USG) && !defined(SVR4) && !defined(__svr4__)
35 #endif /* not __GNUC__ */
38 /* For when compiled as part of the GNU C library. */
44 /* This needs to come after some library #include
45 to get __GNU_LIBRARY__ defined. */
46 #ifdef __GNU_LIBRARY__
50 #else /* Not GNU C library. */
51 #define __alloca alloca
52 #endif /* GNU C library. */
59 /* If GETOPT_COMPAT is defined, `+' as well as `--' can introduce a
60 long-named option. Because this is not POSIX.2 compliant, it is
64 /* This version of `getopt' appears to the caller like standard Unix `getopt'
65 but it behaves differently for the user, since it allows the user
66 to intersperse the options with the other arguments.
68 As `getopt' works, it permutes the elements of ARGV so that,
69 when it is done, all the options precede everything else. Thus
70 all application programs are extended to handle flexible argument order.
72 Setting the environment variable POSIXLY_CORRECT disables permutation.
73 Then the behavior is completely standard.
75 GNU application programs can use a third alternative mode in which
76 they can distinguish the relative order of options and other arguments. */
80 /* For communication from `getopt' to the caller.
81 When `getopt' finds an option that takes an argument,
82 the argument value is returned here.
83 Also, when `ordering' is RETURN_IN_ORDER,
84 each non-option ARGV-element is returned here. */
88 /* Index in ARGV of the next element to be scanned.
89 This is used for communication to and from the caller
90 and for communication between successive calls to `getopt'.
92 On entry to `getopt', zero means this is the first call; initialize.
94 When `getopt' returns EOF, this is the index of the first of the
95 non-option elements that the caller should itself scan.
97 Otherwise, `optind' communicates from one call to the next
98 how much of ARGV has been scanned so far. */
102 /* The next char to be scanned in the option-element
103 in which the last option character we returned was found.
104 This allows us to pick up the scan where we left off.
106 If this is zero, or a null string, it means resume the scan
107 by advancing to the next ARGV-element. */
109 static char *nextchar;
111 /* Callers store zero here to inhibit the error message
112 for unrecognized options. */
116 /* Describe how to deal with options that follow non-option ARGV-elements.
118 If the caller did not specify anything,
119 the default is REQUIRE_ORDER if the environment variable
120 POSIXLY_CORRECT is defined, PERMUTE otherwise.
122 REQUIRE_ORDER means don't recognize them as options;
123 stop option processing when the first non-option is seen.
124 This is what Unix does.
125 This mode of operation is selected by either setting the environment
126 variable POSIXLY_CORRECT, or using `+' as the first character
127 of the list of option characters.
129 PERMUTE is the default. We permute the contents of ARGV as we scan,
130 so that eventually all the non-options are at the end. This allows options
131 to be given in any order, even with programs that were not written to
134 RETURN_IN_ORDER is an option available to programs that were written
135 to expect options and other ARGV-elements in any order and that care about
136 the ordering of the two. We describe each non-option ARGV-element
137 as if it were the argument of an option with character code 1.
138 Using `-' as the first character of the list of option characters
139 selects this mode of operation.
141 The special argument `--' forces an end of option-scanning regardless
142 of the value of `ordering'. In the case of RETURN_IN_ORDER, only
143 `--' can cause `getopt' to return EOF with `optind' != ARGC. */
147 REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER
150 #ifdef __GNU_LIBRARY__
152 #define my_index strchr
153 #define my_bcopy(src, dst, n) memcpy ((dst), (src), (n))
156 /* Avoid depending on library functions or files
157 whose names are inconsistent. */
162 my_index (string, chr)
176 my_bcopy (from, to, size)
181 for (i = 0; i < size; i++)
184 #endif /* GNU C library. */
186 /* Handle permutation of arguments. */
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. */
192 static int first_nonopt;
193 static int last_nonopt;
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.
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. */
208 int nonopts_size = (last_nonopt - first_nonopt) * sizeof (char *);
209 char **temp = (char **) __alloca (nonopts_size);
211 /* Interchange the two blocks of data in ARGV. */
213 my_bcopy (&argv[first_nonopt], temp, nonopts_size);
214 my_bcopy (&argv[last_nonopt], &argv[first_nonopt],
215 (optind - last_nonopt) * sizeof (char *));
216 my_bcopy (temp, &argv[first_nonopt + optind - last_nonopt], nonopts_size);
218 /* Update records for the slots the non-options now occupy. */
220 first_nonopt += (optind - last_nonopt);
221 last_nonopt = optind;
224 /* Scan elements of ARGV (whose length is ARGC) for option characters
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 the option characters
231 from each of the option elements.
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.
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.)
242 OPTSTRING is a string containing the legitimate option characters.
243 If an option character is seen that is not listed in OPTSTRING,
244 return '?' after printing an error message. If you set `opterr' to
245 zero, the error message is suppressed but we still return '?'.
247 If a char in OPTSTRING is followed by a colon, that means it wants an arg,
248 so the following text in the same ARGV-element, or the text of the following
249 ARGV-element, is returned in `optarg'. Two colons mean an option that
250 wants an optional arg; if there is text in the current ARGV-element,
251 it is returned in `optarg', otherwise `optarg' is set to zero.
253 If OPTSTRING starts with `-' or `+', it requests different methods of
254 handling the non-option ARGV-elements.
255 See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
257 Long-named options begin with `--' instead of `-'.
258 Their names may be abbreviated as long as the abbreviation is unique
259 or is an exact match for some defined option. If they have an
260 argument, it follows the option name in the same ARGV-element, separated
261 from the option name by a `=', or else the in next ARGV-element.
262 When `getopt' finds a long-named option, it returns 0 if that option's
263 `flag' field is nonzero, the value of the option's `val' field
264 if the `flag' field is zero.
266 The elements of ARGV aren't really const, because we permute them.
267 But we pretend they're const in the prototype to be compatible
270 LONGOPTS is a vector of `struct option' terminated by an
271 element containing a name which is zero.
273 LONGIND returns the index in LONGOPT of the long-named option found.
274 It is only valid when a long-named option has been found by the most
277 If LONG_ONLY is nonzero, '-' as well as '--' can introduce
278 long-named options. */
281 _getopt_internal (argc, argv, optstring, longopts, longind, long_only)
284 const char *optstring;
285 const struct option *longopts;
293 /* Initialize the internal data when the first call is made.
294 Start processing options with ARGV-element 1 (since ARGV-element 0
295 is the program name); the sequence of previously skipped
296 non-option ARGV-elements is empty. */
300 first_nonopt = last_nonopt = optind = 1;
304 /* Determine how to handle the ordering of options and nonoptions. */
306 if (optstring[0] == '-')
308 ordering = RETURN_IN_ORDER;
311 else if (optstring[0] == '+')
313 ordering = REQUIRE_ORDER;
316 else if (getenv ("POSIXLY_CORRECT") != NULL)
317 ordering = REQUIRE_ORDER;
322 if (nextchar == NULL || *nextchar == '\0')
324 if (ordering == PERMUTE)
326 /* If we have just processed some options following some non-options,
327 exchange them so that the options come first. */
329 if (first_nonopt != last_nonopt && last_nonopt != optind)
330 exchange ((char **) argv);
331 else if (last_nonopt != optind)
332 first_nonopt = optind;
334 /* Now skip any additional non-options
335 and extend the range of non-options previously skipped. */
338 && (argv[optind][0] != '-' || argv[optind][1] == '\0')
341 || argv[optind][0] != '+' || argv[optind][1] == '\0')
342 #endif /* GETOPT_COMPAT */
345 last_nonopt = optind;
348 /* Special ARGV-element `--' means premature end of options.
349 Skip it like a null option,
350 then exchange with previous non-options as if it were an option,
351 then skip everything else like a non-option. */
353 if (optind != argc && !strcmp (argv[optind], "--"))
357 if (first_nonopt != last_nonopt && last_nonopt != optind)
358 exchange ((char **) argv);
359 else if (first_nonopt == last_nonopt)
360 first_nonopt = optind;
366 /* If we have done all the ARGV-elements, stop the scan
367 and back over any non-options that we skipped and permuted. */
371 /* Set the next-arg-index to point at the non-options
372 that we previously skipped, so the caller will digest them. */
373 if (first_nonopt != last_nonopt)
374 optind = first_nonopt;
378 /* If we have come to a non-option and did not permute it,
379 either stop the scan or describe it to the caller and pass it by. */
381 if ((argv[optind][0] != '-' || argv[optind][1] == '\0')
384 || argv[optind][0] != '+' || argv[optind][1] == '\0')
385 #endif /* GETOPT_COMPAT */
388 if (ordering == REQUIRE_ORDER)
390 optarg = argv[optind++];
394 /* We have found another option-ARGV-element.
395 Start decoding its characters. */
397 nextchar = (argv[optind] + 1
398 + (longopts != NULL && argv[optind][1] == '-'));
402 && ((argv[optind][0] == '-'
403 && (argv[optind][1] == '-' || long_only))
405 || argv[optind][0] == '+'
406 #endif /* GETOPT_COMPAT */
409 const struct option *p;
413 const struct option *pfound = NULL;
416 while (*s && *s != '=')
419 /* Test all options for either exact match or abbreviated matches. */
420 for (p = longopts, option_index = 0; p->name;
422 if (!strncmp (p->name, nextchar, s - nextchar))
424 if (s - nextchar == strlen (p->name))
426 /* Exact match found. */
428 indfound = option_index;
432 else if (pfound == NULL)
434 /* First nonexact match found. */
436 indfound = option_index;
439 /* Second nonexact match found. */
446 fprintf (stderr, "%s: option `%s' is ambiguous\n",
447 argv[0], argv[optind]);
448 nextchar += strlen (nextchar);
455 option_index = indfound;
459 /* Don't test has_arg with >, because some C compilers don't
460 allow it to be used on enums. */
467 if (argv[optind - 1][1] == '-')
470 "%s: option `--%s' doesn't allow an argument\n",
471 argv[0], pfound->name);
473 /* +option or -option */
475 "%s: option `%c%s' doesn't allow an argument\n",
476 argv[0], argv[optind - 1][0], pfound->name);
478 nextchar += strlen (nextchar);
482 else if (pfound->has_arg == 1)
485 optarg = argv[optind++];
489 fprintf (stderr, "%s: option `%s' requires an argument\n",
490 argv[0], argv[optind - 1]);
491 nextchar += strlen (nextchar);
495 nextchar += strlen (nextchar);
497 *longind = option_index;
500 *(pfound->flag) = pfound->val;
505 /* Can't find it as a long option. If this is not getopt_long_only,
506 or the option starts with '--' or is not a valid short
507 option, then it's an error.
508 Otherwise interpret it as a short option. */
509 if (!long_only || argv[optind][1] == '-'
511 || argv[optind][0] == '+'
512 #endif /* GETOPT_COMPAT */
513 || my_index (optstring, *nextchar) == NULL)
517 if (argv[optind][1] == '-')
519 fprintf (stderr, "%s: unrecognized option `--%s'\n",
522 /* +option or -option */
523 fprintf (stderr, "%s: unrecognized option `%c%s'\n",
524 argv[0], argv[optind][0], nextchar);
532 /* Look at and handle the next option-character. */
535 char c = *nextchar++;
536 char *temp = my_index (optstring, c);
538 /* Increment `optind' when we start to process its last character. */
539 if (*nextchar == '\0')
542 if (temp == NULL || c == ':')
546 if (c < 040 || c >= 0177)
547 fprintf (stderr, "%s: unrecognized option, character code 0%o\n",
550 fprintf (stderr, "%s: unrecognized option `-%c'\n", argv[0], c);
558 /* This is an option that accepts an argument optionally. */
559 if (*nextchar != '\0')
570 /* This is an option that requires an argument. */
571 if (*nextchar != '\0')
574 /* If we end this ARGV-element by taking the rest as an arg,
575 we must advance to the next element now. */
578 else if (optind == argc)
581 fprintf (stderr, "%s: option `-%c' requires an argument\n",
586 /* We already incremented `optind' once;
587 increment it again when taking next ARGV-elt as argument. */
588 optarg = argv[optind++];
597 getopt (argc, argv, optstring)
600 const char *optstring;
602 return _getopt_internal (argc, argv, optstring,
603 (const struct option *) 0,
610 /* Compile with -DTEST to make an executable for use in testing
611 the above definition of `getopt'. */
619 int digit_optind = 0;
623 int this_option_optind = optind ? optind : 1;
625 c = getopt (argc, argv, "abc:d:0123456789");
641 if (digit_optind != 0 && digit_optind != this_option_optind)
642 printf ("digits occur in two different argv-elements.\n");
643 digit_optind = this_option_optind;
644 printf ("option %c\n", c);
648 printf ("option a\n");
652 printf ("option b\n");
656 printf ("option c with value `%s'\n", optarg);
663 printf ("?? getopt returned character code 0%o ??\n", c);
669 printf ("non-option ARGV-elements: ");
670 while (optind < argc)
671 printf ("%s ", argv[optind++]);