source: tags/gsdl-2_35-distribution/gsdl/src/mgpp/lib/getopt.cpp@ 2444

Last change on this file since 2444 was 2444, checked in by (none), 23 years ago

This commit was manufactured by cvs2svn to create tag
'gsdl-2_35-distribution'.

  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
File size: 20.5 KB
Line 
1/* Getopt for GNU.
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 [email protected]
4 before changing it!
5
6 Copyright (C) 1987, 88, 89, 90, 91, 92, 1993
7 Free Software Foundation, Inc.
8
9 This program is free software; you can redistribute it and/or modify it
10 under the terms of the GNU General Public License as published by the
11 Free Software Foundation; either version 2, or (at your option) any
12 later version.
13
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with this program; if not, write to the Free Software
21 Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */
22
23
24#ifdef HAVE_CONFIG_H
25#include "sysfuncs.h"
26#endif
27
28#if !__STDC__ && !defined(const) && IN_GCC
29#define const
30#endif
31
32/* This tells Alpha OSF/1 not to define a getopt prototype in <stdio.h>. */
33#ifndef _NO_PROTO
34#define _NO_PROTO
35#endif
36
37#include <stdio.h>
38
39/* Comment out all this code if we are using the GNU C Library, and are not
40 actually compiling the library itself. This code is part of the GNU C
41 Library, but also included in many other GNU distributions. Compiling
42 and linking in this code is a waste when using the GNU C library
43 (especially if it is a shared library). Rather than having every GNU
44 program understand `configure --with-gnu-libc' and omit the object files,
45 it is simpler to just do this in the source for each such file. */
46
47#if defined (_LIBC) || !defined (__GNU_LIBRARY__)
48
49
50/* This needs to come after some library #include
51 to get __GNU_LIBRARY__ defined. */
52#ifdef __GNU_LIBRARY__
53/* Don't include stdlib.h for non-GNU C libraries because some of them
54 contain conflicting prototypes for getopt. */
55#include <stdlib.h>
56#endif /* GNU C library. */
57
58/* If GETOPT_COMPAT is defined, `+' as well as `--' can introduce a
59 long-named option. Because this is not POSIX.2 compliant, it is
60 being phased out. */
61/* #define GETOPT_COMPAT */
62
63/* This version of `getopt' appears to the caller like standard Unix `getopt'
64 but it behaves differently for the user, since it allows the user
65 to intersperse the options with the other arguments.
66
67 As `getopt' works, it permutes the elements of ARGV so that,
68 when it is done, all the options precede everything else. Thus
69 all application programs are extended to handle flexible argument order.
70
71 Setting the environment variable POSIXLY_CORRECT disables permutation.
72 Then the behavior is completely standard.
73
74 GNU application programs can use a third alternative mode in which
75 they can distinguish the relative order of options and other arguments. */
76
77#include "getopt.h"
78
79/* For communication from `getopt' to the caller.
80 When `getopt' finds an option that takes an argument,
81 the argument value is returned here.
82 Also, when `ordering' is RETURN_IN_ORDER,
83 each non-option ARGV-element is returned here. */
84
85char *optarg = 0;
86
87/* Index in ARGV of the next element to be scanned.
88 This is used for communication to and from the caller
89 and for communication between successive calls to `getopt'.
90
91 On entry to `getopt', zero means this is the first call; initialize.
92
93 When `getopt' returns EOF, this is the index of the first of the
94 non-option elements that the caller should itself scan.
95
96 Otherwise, `optind' communicates from one call to the next
97 how much of ARGV has been scanned so far. */
98
99/* XXX 1003.2 says this must be 1 before any call. */
100int optind = 0;
101
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.
105
106 If this is zero, or a null string, it means resume the scan
107 by advancing to the next ARGV-element. */
108
109static char *nextchar;
110
111/* Callers store zero here to inhibit the error message
112 for unrecognized options. */
113
114int opterr = 1;
115
116/* Set to an option character which was unrecognized.
117 This must be initialized on some systems to avoid linking in the
118 system's own getopt implementation. */
119
120int optopt = '?';
121
122/* Describe how to deal with options that follow non-option ARGV-elements.
123
124 If the caller did not specify anything,
125 the default is REQUIRE_ORDER if the environment variable
126 POSIXLY_CORRECT is defined, PERMUTE otherwise.
127
128 REQUIRE_ORDER means don't recognize them as options;
129 stop option processing when the first non-option is seen.
130 This is what Unix does.
131 This mode of operation is selected by either setting the environment
132 variable POSIXLY_CORRECT, or using `+' as the first character
133 of the list of option characters.
134
135 PERMUTE is the default. We permute the contents of ARGV as we scan,
136 so that eventually all the non-options are at the end. This allows options
137 to be given in any order, even with programs that were not written to
138 expect this.
139
140 RETURN_IN_ORDER is an option available to programs that were written
141 to expect options and other ARGV-elements in any order and that care about
142 the ordering of the two. We describe each non-option ARGV-element
143 as if it were the argument of an option with character code 1.
144 Using `-' as the first character of the list of option characters
145 selects this mode of operation.
146
147 The special argument `--' forces an end of option-scanning regardless
148 of the value of `ordering'. In the case of RETURN_IN_ORDER, only
149 `--' can cause `getopt' to return EOF with `optind' != ARGC. */
150
151static enum
152 {
153 REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER
154 }
155ordering;
156
157
158#ifdef __GNU_LIBRARY__
159/* We want to avoid inclusion of string.h with non-GNU libraries
160 because there are many ways it can cause trouble.
161 On some systems, it contains special magic macros that don't work
162 in GCC. */
163#include <string.h>
164#define my_index strchr
165#else
166
167/* Avoid depending on library functions or files
168 whose names are inconsistent. */
169
170char *getenv ();
171
172static char *
173my_index (const char *str, int chr)
174{
175 while (*str)
176 {
177 if (*str == chr)
178 return (char *) str;
179 str++;
180 }
181 return 0;
182}
183
184/* If using GCC, we can safely declare strlen this way.
185 If not using GCC, it is ok not to declare it. */
186#ifdef __GNUC__
187#ifdef IN_GCC
188#include "gstddef.h"
189#else
190#include <stddef.h>
191#endif
192extern size_t strlen (const char *);
193#endif
194
195#endif /* GNU C library. */
196
197
198/* Handle permutation of arguments. */
199
200/* Describe the part of ARGV that contains non-options that have
201 been skipped. `first_nonopt' is the index in ARGV of the first of them;
202 `last_nonopt' is the index after the last of them. */
203
204static int first_nonopt;
205static int last_nonopt;
206
207/* Exchange two adjacent subsequences of ARGV.
208 One subsequence is elements [first_nonopt,last_nonopt)
209 which contains all the non-options that have been skipped so far.
210 The other is elements [last_nonopt,optind), which contains all
211 the options processed since those non-options were skipped.
212
213 `first_nonopt' and `last_nonopt' are relocated so that they describe
214 the new indices of the non-options in ARGV after they are moved. */
215
216static void
217exchange (char **argv)
218{
219 int bottom = first_nonopt;
220 int middle = last_nonopt;
221 int top = optind;
222 char *tem;
223
224 /* Exchange the shorter segment with the far end of the longer segment.
225 That puts the shorter segment into the right place.
226 It leaves the longer segment in the right place overall,
227 but it consists of two parts that need to be swapped next. */
228
229 while (top > middle && middle > bottom)
230 {
231 if (top - middle > middle - bottom)
232 {
233 /* Bottom segment is the short one. */
234 int len = middle - bottom;
235 register int i;
236
237 /* Swap it with the top part of the top segment. */
238 for (i = 0; i < len; i++)
239 {
240 tem = argv[bottom + i];
241 argv[bottom + i] = argv[top - (middle - bottom) + i];
242 argv[top - (middle - bottom) + i] = tem;
243 }
244 /* Exclude the moved bottom segment from further swapping. */
245 top -= len;
246 }
247 else
248 {
249 /* Top segment is the short one. */
250 int len = top - middle;
251 register int i;
252
253 /* Swap it with the bottom part of the bottom segment. */
254 for (i = 0; i < len; i++)
255 {
256 tem = argv[bottom + i];
257 argv[bottom + i] = argv[middle + i];
258 argv[middle + i] = tem;
259 }
260 /* Exclude the moved top segment from further swapping. */
261 bottom += len;
262 }
263 }
264
265 /* Update records for the slots the non-options now occupy. */
266
267 first_nonopt += (optind - last_nonopt);
268 last_nonopt = optind;
269}
270
271
272/* Scan elements of ARGV (whose length is ARGC) for option characters
273 given in OPTSTRING.
274
275 If an element of ARGV starts with '-', and is not exactly "-" or "--",
276 then it is an option element. The characters of this element
277 (aside from the initial '-') are option characters. If `getopt'
278 is called repeatedly, it returns successively each of the option characters
279 from each of the option elements.
280
281 If `getopt' finds another option character, it returns that character,
282 updating `optind' and `nextchar' so that the next call to `getopt' can
283 resume the scan with the following option character or ARGV-element.
284
285 If there are no more option characters, `getopt' returns `EOF'.
286 Then `optind' is the index in ARGV of the first ARGV-element
287 that is not an option. (The ARGV-elements have been permuted
288 so that those that are not options now come last.)
289
290 OPTSTRING is a string containing the legitimate option characters.
291 If an option character is seen that is not listed in OPTSTRING,
292 return '?' after printing an error message. If you set `opterr' to
293 zero, the error message is suppressed but we still return '?'.
294
295 If a char in OPTSTRING is followed by a colon, that means it wants an arg,
296 so the following text in the same ARGV-element, or the text of the following
297 ARGV-element, is returned in `optarg'. Two colons mean an option that
298 wants an optional arg; if there is text in the current ARGV-element,
299 it is returned in `optarg', otherwise `optarg' is set to zero.
300
301 If OPTSTRING starts with `-' or `+', it requests different methods of
302 handling the non-option ARGV-elements.
303 See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
304
305 Long-named options begin with `--' instead of `-'.
306 Their names may be abbreviated as long as the abbreviation is unique
307 or is an exact match for some defined option. If they have an
308 argument, it follows the option name in the same ARGV-element, separated
309 from the option name by a `=', or else the in next ARGV-element.
310 When `getopt' finds a long-named option, it returns 0 if that option's
311 `flag' field is nonzero, the value of the option's `val' field
312 if the `flag' field is zero.
313
314 The elements of ARGV aren't really const, because we permute them.
315 But we pretend they're const in the prototype to be compatible
316 with other systems.
317
318 LONGOPTS is a vector of `struct option' terminated by an
319 element containing a name which is zero.
320
321 LONGIND returns the index in LONGOPT of the long-named option found.
322 It is only valid when a long-named option has been found by the most
323 recent call.
324
325 If LONG_ONLY is nonzero, '-' as well as '--' can introduce
326 long-named options. */
327
328int
329_getopt_internal (int argc, char *const *argv, const char *optstring, const struct option *longopts, int *longind, int long_only)
330{
331 int option_index;
332
333 optarg = 0;
334
335 /* Initialize the internal data when the first call is made.
336 Start processing options with ARGV-element 1 (since ARGV-element 0
337 is the program name); the sequence of previously skipped
338 non-option ARGV-elements is empty. */
339
340 if (optind == 0)
341 {
342 first_nonopt = last_nonopt = optind = 1;
343
344 nextchar = NULL;
345
346 /* Determine how to handle the ordering of options and nonoptions. */
347
348 if (optstring[0] == '-')
349 {
350 ordering = RETURN_IN_ORDER;
351 ++optstring;
352 }
353 else if (optstring[0] == '+')
354 {
355 ordering = REQUIRE_ORDER;
356 ++optstring;
357 }
358 else if (getenv ("POSIXLY_CORRECT") != NULL)
359 ordering = REQUIRE_ORDER;
360 else
361 ordering = PERMUTE;
362 }
363
364 if (nextchar == NULL || *nextchar == '\0')
365 {
366 if (ordering == PERMUTE)
367 {
368 /* If we have just processed some options following some non-options,
369 exchange them so that the options come first. */
370
371 if (first_nonopt != last_nonopt && last_nonopt != optind)
372 exchange ((char **) argv);
373 else if (last_nonopt != optind)
374 first_nonopt = optind;
375
376 /* Now skip any additional non-options
377 and extend the range of non-options previously skipped. */
378
379 while (optind < argc
380 && (argv[optind][0] != '-' || argv[optind][1] == '\0')
381#ifdef GETOPT_COMPAT
382 && (longopts == NULL
383 || argv[optind][0] != '+' || argv[optind][1] == '\0')
384#endif /* GETOPT_COMPAT */
385 )
386 optind++;
387 last_nonopt = optind;
388 }
389
390 /* Special ARGV-element `--' means premature end of options.
391 Skip it like a null option,
392 then exchange with previous non-options as if it were an option,
393 then skip everything else like a non-option. */
394
395 if (optind != argc && !strcmp (argv[optind], "--"))
396 {
397 optind++;
398
399 if (first_nonopt != last_nonopt && last_nonopt != optind)
400 exchange ((char **) argv);
401 else if (first_nonopt == last_nonopt)
402 first_nonopt = optind;
403 last_nonopt = argc;
404
405 optind = argc;
406 }
407
408 /* If we have done all the ARGV-elements, stop the scan
409 and back over any non-options that we skipped and permuted. */
410
411 if (optind == argc)
412 {
413 /* Set the next-arg-index to point at the non-options
414 that we previously skipped, so the caller will digest them. */
415 if (first_nonopt != last_nonopt)
416 optind = first_nonopt;
417 return EOF;
418 }
419
420 /* If we have come to a non-option and did not permute it,
421 either stop the scan or describe it to the caller and pass it by. */
422
423 if ((argv[optind][0] != '-' || argv[optind][1] == '\0')
424#ifdef GETOPT_COMPAT
425 && (longopts == NULL
426 || argv[optind][0] != '+' || argv[optind][1] == '\0')
427#endif /* GETOPT_COMPAT */
428 )
429 {
430 if (ordering == REQUIRE_ORDER)
431 return EOF;
432 optarg = argv[optind++];
433 return 1;
434 }
435
436 /* We have found another option-ARGV-element.
437 Start decoding its characters. */
438
439 nextchar = (argv[optind] + 1
440 + (longopts != NULL && argv[optind][1] == '-'));
441 }
442
443 if (longopts != NULL
444 && ((argv[optind][0] == '-'
445 && (argv[optind][1] == '-' || long_only))
446#ifdef GETOPT_COMPAT
447 || argv[optind][0] == '+'
448#endif /* GETOPT_COMPAT */
449 ))
450 {
451 const struct option *p;
452 char *s = nextchar;
453 int exact = 0;
454 int ambig = 0;
455 const struct option *pfound = NULL;
456 int indfound;
457
458 while (*s && *s != '=')
459 s++;
460
461 /* Test all options for either exact match or abbreviated matches. */
462 for (p = longopts, option_index = 0; p->name;
463 p++, option_index++)
464 if (!strncmp (p->name, nextchar, s - nextchar))
465 {
466 if (s - nextchar == strlen (p->name))
467 {
468 /* Exact match found. */
469 pfound = p;
470 indfound = option_index;
471 exact = 1;
472 break;
473 }
474 else if (pfound == NULL)
475 {
476 /* First nonexact match found. */
477 pfound = p;
478 indfound = option_index;
479 }
480 else
481 /* Second nonexact match found. */
482 ambig = 1;
483 }
484
485 if (ambig && !exact)
486 {
487 if (opterr)
488 fprintf (stderr, "%s: option `%s' is ambiguous\n",
489 argv[0], argv[optind]);
490 nextchar += strlen (nextchar);
491 optind++;
492 return '?';
493 }
494
495 if (pfound != NULL)
496 {
497 option_index = indfound;
498 optind++;
499 if (*s)
500 {
501 /* Don't test has_arg with >, because some C compilers don't
502 allow it to be used on enums. */
503 if (pfound->has_arg)
504 optarg = s + 1;
505 else
506 {
507 if (opterr)
508 {
509 if (argv[optind - 1][1] == '-')
510 /* --option */
511 fprintf (stderr,
512 "%s: option `--%s' doesn't allow an argument\n",
513 argv[0], pfound->name);
514 else
515 /* +option or -option */
516 fprintf (stderr,
517 "%s: option `%c%s' doesn't allow an argument\n",
518 argv[0], argv[optind - 1][0], pfound->name);
519 }
520 nextchar += strlen (nextchar);
521 return '?';
522 }
523 }
524 else if (pfound->has_arg == 1)
525 {
526 if (optind < argc)
527 optarg = argv[optind++];
528 else
529 {
530 if (opterr)
531 fprintf (stderr, "%s: option `%s' requires an argument\n",
532 argv[0], argv[optind - 1]);
533 nextchar += strlen (nextchar);
534 return optstring[0] == ':' ? ':' : '?';
535 }
536 }
537 nextchar += strlen (nextchar);
538 if (longind != NULL)
539 *longind = option_index;
540 if (pfound->flag)
541 {
542 *(pfound->flag) = pfound->val;
543 return 0;
544 }
545 return pfound->val;
546 }
547 /* Can't find it as a long option. If this is not getopt_long_only,
548 or the option starts with '--' or is not a valid short
549 option, then it's an error.
550 Otherwise interpret it as a short option. */
551 if (!long_only || argv[optind][1] == '-'
552#ifdef GETOPT_COMPAT
553 || argv[optind][0] == '+'
554#endif /* GETOPT_COMPAT */
555 || my_index (optstring, *nextchar) == NULL)
556 {
557 if (opterr)
558 {
559 if (argv[optind][1] == '-')
560 /* --option */
561 fprintf (stderr, "%s: unrecognized option `--%s'\n",
562 argv[0], nextchar);
563 else
564 /* +option or -option */
565 fprintf (stderr, "%s: unrecognized option `%c%s'\n",
566 argv[0], argv[optind][0], nextchar);
567 }
568 nextchar = (char *) "";
569 optind++;
570 return '?';
571 }
572 }
573
574 /* Look at and handle the next option-character. */
575
576 {
577 char c = *nextchar++;
578 char *temp = my_index (optstring, c);
579
580 /* Increment `optind' when we start to process its last character. */
581 if (*nextchar == '\0')
582 ++optind;
583
584 if (temp == NULL || c == ':')
585 {
586 if (opterr)
587 {
588#if 0
589 if (c < 040 || c >= 0177)
590 fprintf (stderr, "%s: unrecognized option, character code 0%o\n",
591 argv[0], c);
592 else
593 fprintf (stderr, "%s: unrecognized option `-%c'\n", argv[0], c);
594#else
595 /* 1003.2 specifies the format of this message. */
596 fprintf (stderr, "%s: illegal option -- %c\n", argv[0], c);
597#endif
598 }
599 optopt = c;
600 return '?';
601 }
602 if (temp[1] == ':')
603 {
604 if (temp[2] == ':')
605 {
606 /* This is an option that accepts an argument optionally. */
607 if (*nextchar != '\0')
608 {
609 optarg = nextchar;
610 optind++;
611 }
612 else
613 optarg = 0;
614 nextchar = NULL;
615 }
616 else
617 {
618 /* This is an option that requires an argument. */
619 if (*nextchar != '\0')
620 {
621 optarg = nextchar;
622 /* If we end this ARGV-element by taking the rest as an arg,
623 we must advance to the next element now. */
624 optind++;
625 }
626 else if (optind == argc)
627 {
628 if (opterr)
629 {
630#if 0
631 fprintf (stderr, "%s: option `-%c' requires an argument\n",
632 argv[0], c);
633#else
634 /* 1003.2 specifies the format of this message. */
635 fprintf (stderr, "%s: option requires an argument -- %c\n",
636 argv[0], c);
637#endif
638 }
639 optopt = c;
640 if (optstring[0] == ':')
641 c = ':';
642 else
643 c = '?';
644 }
645 else
646 /* We already incremented `optind' once;
647 increment it again when taking next ARGV-elt as argument. */
648 optarg = argv[optind++];
649 nextchar = NULL;
650 }
651 }
652 return c;
653 }
654}
655
656int
657getopt (int argc, char *const *argv, const char *optstring)
658{
659 return _getopt_internal (argc, argv, optstring,
660 (const struct option *) 0,
661 (int *) 0,
662 0);
663}
664
665#endif /* _LIBC or not __GNU_LIBRARY__. */
666
667
668#ifdef TEST
669
670/* Compile with -DTEST to make an executable for use in testing
671 the above definition of `getopt'. */
672
673int
674main (int argc, char **argv)
675{
676 int c;
677 int digit_optind = 0;
678
679 while (1)
680 {
681 int this_option_optind = optind ? optind : 1;
682
683 c = getopt (argc, argv, "abc:d:0123456789");
684 if (c == EOF)
685 break;
686
687 switch (c)
688 {
689 case '0':
690 case '1':
691 case '2':
692 case '3':
693 case '4':
694 case '5':
695 case '6':
696 case '7':
697 case '8':
698 case '9':
699 if (digit_optind != 0 && digit_optind != this_option_optind)
700 printf ("digits occur in two different argv-elements.\n");
701 digit_optind = this_option_optind;
702 printf ("option %c\n", c);
703 break;
704
705 case 'a':
706 printf ("option a\n");
707 break;
708
709 case 'b':
710 printf ("option b\n");
711 break;
712
713 case 'c':
714 printf ("option c with value `%s'\n", optarg);
715 break;
716
717 case '?':
718 break;
719
720 default:
721 printf ("?? getopt returned character code 0%o ??\n", c);
722 }
723 }
724
725 if (optind < argc)
726 {
727 printf ("non-option ARGV-elements: ");
728 while (optind < argc)
729 printf ("%s ", argv[optind++]);
730 printf ("\n");
731 }
732
733 exit (0);
734}
735
736#endif /* TEST */
Note: See TracBrowser for help on using the repository browser.