Debian Codegraph @

lib/getopt.c

raw
1 /* Getopt for GNU.
2 Copyright (C) 1987-2026 Free Software Foundation, Inc.
3 This file is part of the GNU C Library and is also part of gnulib.
4 Patches to this file should be submitted to both projects.
5
6 The GNU C Library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Lesser General Public
8 License as published by the Free Software Foundation; either
9 version 2.1 of the License, or (at your option) any later version.
10
11 The GNU C Library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public
17 License along with the GNU C Library; if not, see
18 <https://www.gnu.org/licenses/>. */
19
20 #ifndef _LIBC
21 # include <config.h>
22 #endif
23
24 #include <getopt.h>
25
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <unistd.h>
30
31 #ifdef _LIBC
32 /* When used as part of glibc, error printing must be done differently
33 for standards compliance. getopt is not a cancellation point, so
34 it must not call functions that are, and it is specified by an
35 older standard than stdio locking, so it must not refer to
36 functions in the "user namespace" related to stdio locking.
37 Finally, it must use glibc's internal message translation so that
38 the messages are looked up in the proper text domain. */
39 # include <libintl.h>
40 # define fprintf __fxprintf_nocancel
41 # define flockfile(fp) _IO_flockfile (fp)
42 # define funlockfile(fp) _IO_funlockfile (fp)
43 #else
44 # include "gettext.h"
45 # define _(msgid) dgettext (GNULIB_TEXT_DOMAIN, msgid)
46 /* When used standalone, flockfile and funlockfile might not be
47 available. */
48 # if (!defined _POSIX_THREAD_SAFE_FUNCTIONS \
49 || (defined _WIN32 && ! defined __CYGWIN__))
50 # define flockfile(fp) /* nop */
51 # define funlockfile(fp) /* nop */
52 # endif
53 /* When used standalone, do not attempt to use alloca. */
54 # define __libc_use_alloca(size) 0
55 # undef alloca
56 # define alloca(size) (abort (), (void *)0)
57 #endif
58
59 /* This implementation of 'getopt' has three modes for handling
60 options interspersed with non-option arguments. It can stop
61 scanning for options at the first non-option argument encountered,
62 as POSIX specifies. It can continue scanning for options after the
63 first non-option argument, but permute 'argv' as it goes so that,
64 after 'getopt' is done, all the options precede all the non-option
65 arguments and 'optind' points to the first non-option argument.
66 Or, it can report non-option arguments as if they were arguments to
67 the option character '\x01'.
68
69 The default behavior of 'getopt_long' is to permute the argument list.
70 When this implementation is used standalone, the default behavior of
71 'getopt' is to stop at the first non-option argument, but when it is
72 used as part of GNU libc it also permutes the argument list. In both
73 cases, setting the environment variable POSIXLY_CORRECT to any value
74 disables permutation.
75
76 If the first character of the OPTSTRING argument to 'getopt' or
77 'getopt_long' is '+', both functions will stop at the first
78 non-option argument. If it is '-', both functions will report
79 non-option arguments as arguments to the option character '\x01'. */
80
81 #include "getopt_int.h"
82
83 /* For communication from 'getopt' to the caller.
84 When 'getopt' finds an option that takes an argument,
85 the argument value is returned here.
86 Also, when 'ordering' is RETURN_IN_ORDER,
87 each non-option ARGV-element is returned here. */
88
89 char *optarg;
90
91 /* Index in ARGV of the next element to be scanned.
92 This is used for communication to and from the caller
93 and for communication between successive calls to 'getopt'.
94
95 On entry to 'getopt', zero means this is the first call; initialize.
96
97 When 'getopt' returns -1, this is the index of the first of the
98 non-option elements that the caller should itself scan.
99
100 Otherwise, 'optind' communicates from one call to the next
101 how much of ARGV has been scanned so far. */
102
103 /* 1003.2 says this must be 1 before any call. */
104 int optind = 1;
105
106 /* Callers store zero here to inhibit the error message
107 for unrecognized options. */
108
109 int opterr = 1;
110
111 /* Set to an option character which was unrecognized.
112 This must be initialized on some systems to avoid linking in the
113 system's own getopt implementation. */
114
115 int optopt = '?';
116
117 /* Keep a global copy of all internal members of getopt_data. */
118
119 static struct _getopt_data getopt_data;
120
121 /* Exchange two adjacent subsequences of ARGV.
122 One subsequence is elements [first_nonopt,last_nonopt)
123 which contains all the non-options that have been skipped so far.
124 The other is elements [last_nonopt,optind), which contains all
125 the options processed since those non-options were skipped.
126
127 'first_nonopt' and 'last_nonopt' are relocated so that they describe
128 the new indices of the non-options in ARGV after they are moved. */
129
130 static void
131 exchange (char **argv, struct _getopt_data *d)
132 {
133 int bottom = d->__first_nonopt;
134 int middle = d->__last_nonopt;
135 int top = d->optind;
136
137 /* Exchange the shorter segment with the far end of the longer segment.
138 That puts the shorter segment into the right place.
139 It leaves the longer segment in the right place overall,
140 but it consists of two parts that need to be swapped next. */
141
142 while (top > middle && middle > bottom)
143 {
144 if (top - middle > middle - bottom)
145 {
146 /* Bottom segment is the short one. */
147 int len = middle - bottom;
148 int i;
149
150 /* Swap it with the top part of the top segment. */
151 for (i = 0; i < len; i++)
152 {
153 char *tem = argv[bottom + i];
154 argv[bottom + i] = argv[top - (middle - bottom) + i];
155 argv[top - (middle - bottom) + i] = tem;
156 }
157 /* Exclude the moved bottom segment from further swapping. */
158 top -= len;
159 }
160 else
161 {
162 /* Top segment is the short one. */
163 int len = top - middle;
164 int i;
165
166 /* Swap it with the bottom part of the bottom segment. */
167 for (i = 0; i < len; i++)
168 {
169 char *tem = argv[bottom + i];
170 argv[bottom + i] = argv[middle + i];
171 argv[middle + i] = tem;
172 }
173 /* Exclude the moved top segment from further swapping. */
174 bottom += len;
175 }
176 }
177
178 /* Update records for the slots the non-options now occupy. */
179
180 d->__first_nonopt += (d->optind - d->__last_nonopt);
181 d->__last_nonopt = d->optind;
182 }
183
184 /* Process the argument starting with d->__nextchar as a long option.
185 d->optind should *not* have been advanced over this argument.
186
187 If the value returned is -1, it was not actually a long option, the
188 state is unchanged, and the argument should be processed as a set
189 of short options (this can only happen when long_only is true).
190 Otherwise, the option (and its argument, if any) have been consumed
191 and the return value is the value to return from _getopt_internal_r. */
192 static int
193 process_long_option (int argc, char **argv, const char *optstring,
194 const struct option *longopts, int *longind,
195 int long_only, struct _getopt_data *d,
196 int print_errors, const char *prefix)
197 {
198
199 char *nameend;
200 for (nameend = d->__nextchar; *nameend && *nameend != '='; nameend++)
201 /* Do nothing. */ ;
202 size_t namelen = nameend - d->__nextchar;
203
204 /* First look for an exact match, counting the options as a side
205 effect. */
206 const struct option *pfound = NULL;
207 int n_options;
208 int option_index;
209 {
210 const struct option *p;
211 for (p = longopts, n_options = 0; p->name; p++, n_options++)
212 if (!strncmp (p->name, d->__nextchar, namelen)
213 && namelen == strlen (p->name))
214 {
215 /* Exact match found. */
216 pfound = p;
217 option_index = n_options;
218 break;
219 }
220 }
221
222 if (pfound == NULL)
223 {
224 /* Didn't find an exact match, so look for abbreviations. */
225 unsigned char *ambig_set = NULL;
226 /* Use simpler fallback diagnostic if ambig_set == &ambig_fallback. */
227 unsigned char ambig_fallback;
228 void *ambig_malloced = NULL;
229 int indfound = -1;
230 const struct option *p;
231
232 for (p = longopts, option_index = 0; p->name; p++, option_index++)
233 if (!strncmp (p->name, d->__nextchar, namelen))
234 {
235 if (pfound == NULL)
236 {
237 /* First nonexact match found. */
238 pfound = p;
239 indfound = option_index;
240 }
241 else if (long_only
242 || pfound->has_arg != p->has_arg
243 || pfound->flag != p->flag
244 || pfound->val != p->val)
245 {
246 /* Second or later nonexact match found. */
247 if (ambig_set != &ambig_fallback)
248 {
249 if (!print_errors)
250 /* Don't waste effort tracking the ambig set if
251 we're not going to print it anyway. */
252 ambig_set = &ambig_fallback;
253 else if (!ambig_set)
254 {
255 if (__libc_use_alloca (n_options))
256 ambig_set = alloca (n_options);
257 else
258 {
259 ambig_malloced = malloc (n_options);
260 /* Fall back to simpler diagnostic if
261 memory allocation fails. */
262 ambig_set = (ambig_malloced ? ambig_malloced
263 : &ambig_fallback);
264 }
265
266 if (ambig_set != &ambig_fallback)
267 {
268 memset (ambig_set, 0, n_options);
269 ambig_set[indfound] = 1;
270 }
271 }
272 if (ambig_set && ambig_set != &ambig_fallback)
273 ambig_set[option_index] = 1;
274 }
275 }
276 }
277
278 if (ambig_set)
279 {
280 if (print_errors)
281 {
282 if (ambig_set == &ambig_fallback)
283 fprintf (stderr, _("%s: option '%s%s' is ambiguous\n"),
284 argv[0], prefix, d->__nextchar);
285 else
286 {
287 flockfile (stderr);
288 fprintf (stderr,
289 _("%s: option '%s%s' is ambiguous; possibilities:"),
290 argv[0], prefix, d->__nextchar);
291
292 for (option_index = 0; option_index < n_options; option_index++)
293 if (ambig_set[option_index])
294 fprintf (stderr, " '%s%s'",
295 prefix, longopts[option_index].name);
296
297 /* This must use 'fprintf' even though it's only
298 printing a single character, so that it goes through
299 __fxprintf_nocancel when compiled as part of glibc. */
300 fprintf (stderr, "\n");
301 funlockfile (stderr);
302 }
303 }
304 free (ambig_malloced);
305 d->__nextchar += strlen (d->__nextchar);
306 d->optind++;
307 d->optopt = 0;
308 return '?';
309 }
310
311 option_index = indfound;
312 }
313
314 if (pfound == NULL)
315 {
316 /* Can't find it as a long option. If this is not getopt_long_only,
317 or the option starts with '--' or is not a valid short option,
318 then it's an error. */
319 if (!long_only || argv[d->optind][1] == '-'
320 || strchr (optstring, *d->__nextchar) == NULL)
321 {
322 if (print_errors)
323 fprintf (stderr, _("%s: unrecognized option '%s%s'\n"),
324 argv[0], prefix, d->__nextchar);
325
326 d->__nextchar = NULL;
327 d->optind++;
328 d->optopt = 0;
329 return '?';
330 }
331
332 /* Otherwise interpret it as a short option. */
333 return -1;
334 }
335
336 /* We have found a matching long option. Consume it. */
337 d->optind++;
338 d->__nextchar = NULL;
339 if (*nameend)
340 {
341 /* Don't test has_arg with >, because some C compilers don't
342 allow it to be used on enums. */
343 if (pfound->has_arg)
344 d->optarg = nameend + 1;
345 else
346 {
347 if (print_errors)
348 fprintf (stderr,
349 _("%s: option '%s%s' doesn't allow an argument\n"),
350 argv[0], prefix, pfound->name);
351
352 d->optopt = pfound->val;
353 return '?';
354 }
355 }
356 else if (pfound->has_arg == 1)
357 {
358 if (d->optind < argc)
359 d->optarg = argv[d->optind++];
360 else
361 {
362 if (print_errors)
363 fprintf (stderr,
364 _("%s: option '%s%s' requires an argument\n"),
365 argv[0], prefix, pfound->name);
366
367 d->optopt = pfound->val;
368 return optstring[0] == ':' ? ':' : '?';
369 }
370 }
371
372 if (longind != NULL)
373 *longind = option_index;
374 if (pfound->flag)
375 {
376 *(pfound->flag) = pfound->val;
377 return 0;
378 }
379 return pfound->val;
380 }
381
382 /* Initialize internal data upon the first call to getopt. */
383
384 static const char *
385 _getopt_initialize (_GL_UNUSED int argc,
386 _GL_UNUSED char **argv, const char *optstring,
387 struct _getopt_data *d, int posixly_correct)
388 {
389 /* Start processing options with ARGV-element 1 (since ARGV-element 0
390 is the program name); the sequence of previously skipped
391 non-option ARGV-elements is empty. */
392 if (d->optind == 0)
393 d->optind = 1;
394
395 d->__first_nonopt = d->__last_nonopt = d->optind;
396 d->__nextchar = NULL;
397
398 /* Determine how to handle the ordering of options and nonoptions. */
399 if (optstring[0] == '-')
400 {
401 d->__ordering = RETURN_IN_ORDER;
402 ++optstring;
403 }
404 else if (optstring[0] == '+')
405 {
406 d->__ordering = REQUIRE_ORDER;
407 ++optstring;
408 }
409 else if (posixly_correct || !!getenv ("POSIXLY_CORRECT"))
410 d->__ordering = REQUIRE_ORDER;
411 else
412 d->__ordering = PERMUTE;
413
414 d->__initialized = 1;
415 return optstring;
416 }
417
418 /* Scan elements of ARGV (whose length is ARGC) for option characters
419 given in OPTSTRING.
420
421 If an element of ARGV starts with '-', and is not exactly "-" or "--",
422 then it is an option element. The characters of this element
423 (aside from the initial '-') are option characters. If 'getopt'
424 is called repeatedly, it returns successively each of the option characters
425 from each of the option elements.
426
427 If 'getopt' finds another option character, it returns that character,
428 updating 'optind' and 'nextchar' so that the next call to 'getopt' can
429 resume the scan with the following option character or ARGV-element.
430
431 If there are no more option characters, 'getopt' returns -1.
432 Then 'optind' is the index in ARGV of the first ARGV-element
433 that is not an option. (The ARGV-elements have been permuted
434 so that those that are not options now come last.)
435
436 OPTSTRING is a string containing the legitimate option characters.
437 If an option character is seen that is not listed in OPTSTRING,
438 return '?' after printing an error message. If you set 'opterr' to
439 zero, the error message is suppressed but we still return '?'.
440
441 If a char in OPTSTRING is followed by a colon, that means it wants an arg,
442 so the following text in the same ARGV-element, or the text of the following
443 ARGV-element, is returned in 'optarg'. Two colons mean an option that
444 wants an optional arg; if there is text in the current ARGV-element,
445 it is returned in 'optarg', otherwise 'optarg' is set to zero.
446
447 If OPTSTRING starts with '-' or '+', it requests different methods of
448 handling the non-option ARGV-elements.
449 See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
450
451 Long-named options begin with '--' instead of '-'.
452 Their names may be abbreviated as long as the abbreviation is unique
453 or is an exact match for some defined option. If they have an
454 argument, it follows the option name in the same ARGV-element, separated
455 from the option name by a '=', or else the in next ARGV-element.
456 When 'getopt' finds a long-named option, it returns 0 if that option's
457 'flag' field is nonzero, the value of the option's 'val' field
458 if the 'flag' field is zero.
459
460 The elements of ARGV aren't really const, because we permute them.
461 But we pretend they're const in the prototype to be compatible
462 with other systems.
463
464 LONGOPTS is a vector of 'struct option' terminated by an
465 element containing a name which is zero.
466
467 LONGIND returns the index in LONGOPT of the long-named option found.
468 It is only valid when a long-named option has been found by the most
469 recent call.
470
471 If LONG_ONLY is nonzero, '-' as well as '--' can introduce
472 long-named options. */
473
474 int
475 _getopt_internal_r (int argc, char **argv, const char *optstring,
476 const struct option *longopts, int *longind,
477 int long_only, struct _getopt_data *d, int posixly_correct)
478 {
479 if (argc < 1)
480 return -1;
481
482 int print_errors = d->opterr;
483
484 d->optarg = NULL;
485
486 if (d->optind == 0 || !d->__initialized)
487 optstring = _getopt_initialize (argc, argv, optstring, d, posixly_correct);
488 else if (optstring[0] == '-' || optstring[0] == '+')
489 optstring++;
490
491 if (optstring[0] == ':')
492 print_errors = 0;
493
494 /* Test whether ARGV[optind] points to a non-option argument. */
495 #define NONOPTION_P (argv[d->optind][0] != '-' || argv[d->optind][1] == '\0')
496
497 if (d->__nextchar == NULL || *d->__nextchar == '\0')
498 {
499 /* Advance to the next ARGV-element. */
500
501 /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
502 moved back by the user (who may also have changed the arguments). */
503 if (d->__last_nonopt > d->optind)
504 d->__last_nonopt = d->optind;
505 if (d->__first_nonopt > d->optind)
506 d->__first_nonopt = d->optind;
507
508 if (d->__ordering == PERMUTE)
509 {
510 /* If we have just processed some options following some non-options,
511 exchange them so that the options come first. */
512
513 if (d->__first_nonopt != d->__last_nonopt
514 && d->__last_nonopt != d->optind)
515 exchange (argv, d);
516 else if (d->__last_nonopt != d->optind)
517 d->__first_nonopt = d->optind;
518
519 /* Skip any additional non-options
520 and extend the range of non-options previously skipped. */
521
522 while (d->optind < argc && NONOPTION_P)
523 d->optind++;
524 d->__last_nonopt = d->optind;
525 }
526
527 /* The special ARGV-element '--' means premature end of options.
528 Skip it like a null option,
529 then exchange with previous non-options as if it were an option,
530 then skip everything else like a non-option. */
531
532 if (d->optind != argc && !strcmp (argv[d->optind], "--"))
533 {
534 d->optind++;
535
536 if (d->__first_nonopt != d->__last_nonopt
537 && d->__last_nonopt != d->optind)
538 exchange (argv, d);
539 else if (d->__first_nonopt == d->__last_nonopt)
540 d->__first_nonopt = d->optind;
541 d->__last_nonopt = argc;
542
543 d->optind = argc;
544 }
545
546 /* If we have done all the ARGV-elements, stop the scan
547 and back over any non-options that we skipped and permuted. */
548
549 if (d->optind == argc)
550 {
551 /* Set the next-arg-index to point at the non-options
552 that we previously skipped, so the caller will digest them. */
553 if (d->__first_nonopt != d->__last_nonopt)
554 d->optind = d->__first_nonopt;
555 return -1;
556 }
557
558 /* If we have come to a non-option and did not permute it,
559 either stop the scan or describe it to the caller and pass it by. */
560
561 if (NONOPTION_P)
562 {
563 if (d->__ordering == REQUIRE_ORDER)
564 return -1;
565 d->optarg = argv[d->optind++];
566 return 1;
567 }
568
569 /* We have found another option-ARGV-element.
570 Check whether it might be a long option. */
571 if (longopts)
572 {
573 if (argv[d->optind][1] == '-')
574 {
575 /* "--foo" is always a long option. The special option
576 "--" was handled above. */
577 d->__nextchar = argv[d->optind] + 2;
578 return process_long_option (argc, argv, optstring, longopts,
579 longind, long_only, d,
580 print_errors, "--");
581 }
582
583 /* If long_only and the ARGV-element has the form "-f",
584 where f is a valid short option, don't consider it an
585 abbreviated form of a long option that starts with f.
586 Otherwise there would be no way to give the -f short
587 option.
588
589 On the other hand, if there's a long option "fubar" and
590 the ARGV-element is "-fu", do consider that an
591 abbreviation of the long option, just like "--fu", and
592 not "-f" with arg "u".
593
594 This distinction seems to be the most useful approach. */
595 if (long_only && (argv[d->optind][2]
596 || !strchr (optstring, argv[d->optind][1])))
597 {
598 d->__nextchar = argv[d->optind] + 1;
599 int code = process_long_option (argc, argv, optstring, longopts,
600 longind, long_only, d,
601 print_errors, "-");
602 if (code != -1)
603 return code;
604 }
605 }
606
607 /* It is not a long option. Skip the initial punctuation. */
608 d->__nextchar = argv[d->optind] + 1;
609 }
610
611 /* Look at and handle the next short option-character. */
612
613 {
614 char c = *d->__nextchar++;
615 const char *temp = strchr (optstring, c);
616
617 /* Increment 'optind' when we start to process its last character. */
618 if (*d->__nextchar == '\0')
619 ++d->optind;
620
621 if (temp == NULL || c == ':' || c == ';')
622 {
623 if (print_errors)
624 fprintf (stderr, _("%s: invalid option -- '%c'\n"), argv[0], c);
625 d->optopt = c;
626 return '?';
627 }
628
629 /* Convenience. Treat POSIX -W foo same as long option --foo */
630 if (temp[0] == 'W' && temp[1] == ';' && longopts != NULL)
631 {
632 /* This is an option that requires an argument. */
633 if (*d->__nextchar != '\0')
634 d->optarg = d->__nextchar;
635 else if (d->optind == argc)
636 {
637 if (print_errors)
638 fprintf (stderr,
639 _("%s: option requires an argument -- '%c'\n"),
640 argv[0], c);
641
642 d->optopt = c;
643 if (optstring[0] == ':')
644 c = ':';
645 else
646 c = '?';
647 return c;
648 }
649 else
650 d->optarg = argv[d->optind];
651
652 d->__nextchar = d->optarg;
653 d->optarg = NULL;
654 return process_long_option (argc, argv, optstring, longopts, longind,
655 0 /* long_only */, d, print_errors, "-W ");
656 }
657 if (temp[1] == ':')
658 {
659 if (temp[2] == ':')
660 {
661 /* This is an option that accepts an argument optionally. */
662 if (*d->__nextchar != '\0')
663 {
664 d->optarg = d->__nextchar;
665 d->optind++;
666 }
667 else
668 d->optarg = NULL;
669 d->__nextchar = NULL;
670 }
671 else
672 {
673 /* This is an option that requires an argument. */
674 if (*d->__nextchar != '\0')
675 {
676 d->optarg = d->__nextchar;
677 /* If we end this ARGV-element by taking the rest as an arg,
678 we must advance to the next element now. */
679 d->optind++;
680 }
681 else if (d->optind == argc)
682 {
683 if (print_errors)
684 fprintf (stderr,
685 _("%s: option requires an argument -- '%c'\n"),
686 argv[0], c);
687
688 d->optopt = c;
689 if (optstring[0] == ':')
690 c = ':';
691 else
692 c = '?';
693 }
694 else
695 /* We already incremented 'optind' once;
696 increment it again when taking next ARGV-elt as argument. */
697 d->optarg = argv[d->optind++];
698 d->__nextchar = NULL;
699 }
700 }
701 return c;
702 }
703 }
704
705 int
706 _getopt_internal (int argc, char **argv, const char *optstring,
707 const struct option *longopts, int *longind, int long_only,
708 int posixly_correct)
709 {
710 getopt_data.optind = optind;
711 getopt_data.opterr = opterr;
712
713 int result = _getopt_internal_r (argc, argv, optstring, longopts,
714 longind, long_only, &getopt_data,
715 posixly_correct);
716
717 optind = getopt_data.optind;
718 optarg = getopt_data.optarg;
719 optopt = getopt_data.optopt;
720
721 return result;
722 }
723
724 /* glibc gets a LSB-compliant getopt and a POSIX-compliant __posix_getopt.
725 Standalone applications just get a POSIX-compliant getopt.
726 POSIX and LSB both require these functions to take 'char *const *argv'
727 even though this is incorrect (because of the permutation). */
728 #define GETOPT_ENTRY(NAME, POSIXLY_CORRECT) \
729 int \
730 NAME (int argc, char *const *argv, const char *optstring) \
731 { \
732 return _getopt_internal (argc, (char **)argv, optstring, \
733 NULL, NULL, 0, POSIXLY_CORRECT); \
734 }
735
736 #ifdef _LIBC
737 GETOPT_ENTRY(getopt, 0)
738 GETOPT_ENTRY(__posix_getopt, 1)
739 #else
740 GETOPT_ENTRY(getopt, 1)
741 #endif
742
743
744 #ifdef TEST
745
746 /* Compile with -DTEST to make an executable for use in testing
747 the above definition of 'getopt'. */
748
749 int
750 main (int argc, char **argv)
751 {
752 int digit_optind = 0;
753
754 while (1)
755 {
756 int this_option_optind = optind ? optind : 1;
757
758 int c = getopt (argc, argv, "abc:d:0123456789");
759 if (c == -1)
760 break;
761
762 switch (c)
763 {
764 case '0':
765 case '1':
766 case '2':
767 case '3':
768 case '4':
769 case '5':
770 case '6':
771 case '7':
772 case '8':
773 case '9':
774 if (digit_optind != 0 && digit_optind != this_option_optind)
775 printf ("digits occur in two different argv-elements.\n");
776 digit_optind = this_option_optind;
777 printf ("option %c\n", c);
778 break;
779
780 case 'a':
781 printf ("option a\n");
782 break;
783
784 case 'b':
785 printf ("option b\n");
786 break;
787
788 case 'c':
789 printf ("option c with value '%s'\n", optarg);
790 break;
791
792 case '?':
793 break;
794
795 default:
796 printf ("?? getopt returned character code 0%o ??\n", c);
797 }
798 }
799
800 if (optind < argc)
801 {
802 printf ("non-option ARGV-elements: ");
803 while (optind < argc)
804 printf ("%s ", argv[optind++]);
805 printf ("\n");
806 }
807
808 exit (0);
809 }
810
811 #endif /* TEST */