source: trunk/gsdl/src/mgpp/lib/getopt.cpp@ 855

Last change on this file since 855 was 855, checked in by sjboddie, 24 years ago

Rodgers new C++ mg

  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
File size: 20.7 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 (str, chr)
174 const char *str;
175 int chr;
176{
177 while (*str)
178 {
179 if (*str == chr)
180 return (char *) str;
181 str++;
182 }
183 return 0;
184}
185
186/* If using GCC, we can safely declare strlen this way.
187 If not using GCC, it is ok not to declare it. */
188#ifdef __GNUC__
189#ifdef IN_GCC
190#include "gstddef.h"
191#else
192#include <stddef.h>
193#endif
194extern size_t strlen (const char *);
195#endif
196
197#endif /* GNU C library. */
198
199
200/* Handle permutation of arguments. */
201
202/* Describe the part of ARGV that contains non-options that have
203 been skipped. `first_nonopt' is the index in ARGV of the first of them;
204 `last_nonopt' is the index after the last of them. */
205
206static int first_nonopt;
207static int last_nonopt;
208
209/* Exchange two adjacent subsequences of ARGV.
210 One subsequence is elements [first_nonopt,last_nonopt)
211 which contains all the non-options that have been skipped so far.
212 The other is elements [last_nonopt,optind), which contains all
213 the options processed since those non-options were skipped.
214
215 `first_nonopt' and `last_nonopt' are relocated so that they describe
216 the new indices of the non-options in ARGV after they are moved. */
217
218static void
219exchange (argv)
220 char **argv;
221{
222 int bottom = first_nonopt;
223 int middle = last_nonopt;
224 int top = optind;
225 char *tem;
226
227 /* Exchange the shorter segment with the far end of the longer segment.
228 That puts the shorter segment into the right place.
229 It leaves the longer segment in the right place overall,
230 but it consists of two parts that need to be swapped next. */
231
232 while (top > middle && middle > bottom)
233 {
234 if (top - middle > middle - bottom)
235 {
236 /* Bottom segment is the short one. */
237 int len = middle - bottom;
238 register int i;
239
240 /* Swap it with the top part of the top segment. */
241 for (i = 0; i < len; i++)
242 {
243 tem = argv[bottom + i];
244 argv[bottom + i] = argv[top - (middle - bottom) + i];
245 argv[top - (middle - bottom) + i] = tem;
246 }
247 /* Exclude the moved bottom segment from further swapping. */
248 top -= len;
249 }
250 else
251 {
252 /* Top segment is the short one. */
253 int len = top - middle;
254 register int i;
255
256 /* Swap it with the bottom part of the bottom segment. */
257 for (i = 0; i < len; i++)
258 {
259 tem = argv[bottom + i];
260 argv[bottom + i] = argv[middle + i];
261 argv[middle + i] = tem;
262 }
263 /* Exclude the moved top segment from further swapping. */
264 bottom += len;
265 }
266 }
267
268 /* Update records for the slots the non-options now occupy. */
269
270 first_nonopt += (optind - last_nonopt);
271 last_nonopt = optind;
272}
273
274
275/* Scan elements of ARGV (whose length is ARGC) for option characters
276 given in OPTSTRING.
277
278 If an element of ARGV starts with '-', and is not exactly "-" or "--",
279 then it is an option element. The characters of this element
280 (aside from the initial '-') are option characters. If `getopt'
281 is called repeatedly, it returns successively each of the option characters
282 from each of the option elements.
283
284 If `getopt' finds another option character, it returns that character,
285 updating `optind' and `nextchar' so that the next call to `getopt' can
286 resume the scan with the following option character or ARGV-element.
287
288 If there are no more option characters, `getopt' returns `EOF'.
289 Then `optind' is the index in ARGV of the first ARGV-element
290 that is not an option. (The ARGV-elements have been permuted
291 so that those that are not options now come last.)
292
293 OPTSTRING is a string containing the legitimate option characters.
294 If an option character is seen that is not listed in OPTSTRING,
295 return '?' after printing an error message. If you set `opterr' to
296 zero, the error message is suppressed but we still return '?'.
297
298 If a char in OPTSTRING is followed by a colon, that means it wants an arg,
299 so the following text in the same ARGV-element, or the text of the following
300 ARGV-element, is returned in `optarg'. Two colons mean an option that
301 wants an optional arg; if there is text in the current ARGV-element,
302 it is returned in `optarg', otherwise `optarg' is set to zero.
303
304 If OPTSTRING starts with `-' or `+', it requests different methods of
305 handling the non-option ARGV-elements.
306 See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
307
308 Long-named options begin with `--' instead of `-'.
309 Their names may be abbreviated as long as the abbreviation is unique
310 or is an exact match for some defined option. If they have an
311 argument, it follows the option name in the same ARGV-element, separated
312 from the option name by a `=', or else the in next ARGV-element.
313 When `getopt' finds a long-named option, it returns 0 if that option's
314 `flag' field is nonzero, the value of the option's `val' field
315 if the `flag' field is zero.
316
317 The elements of ARGV aren't really const, because we permute them.
318 But we pretend they're const in the prototype to be compatible
319 with other systems.
320
321 LONGOPTS is a vector of `struct option' terminated by an
322 element containing a name which is zero.
323
324 LONGIND returns the index in LONGOPT of the long-named option found.
325 It is only valid when a long-named option has been found by the most
326 recent call.
327
328 If LONG_ONLY is nonzero, '-' as well as '--' can introduce
329 long-named options. */
330
331int
332_getopt_internal (argc, argv, optstring, longopts, longind, long_only)
333 int argc;
334 char *const *argv;
335 const char *optstring;
336 const struct option *longopts;
337 int *longind;
338 int long_only;
339{
340 int option_index;
341
342 optarg = 0;
343
344 /* Initialize the internal data when the first call is made.
345 Start processing options with ARGV-element 1 (since ARGV-element 0
346 is the program name); the sequence of previously skipped
347 non-option ARGV-elements is empty. */
348
349 if (optind == 0)
350 {
351 first_nonopt = last_nonopt = optind = 1;
352
353 nextchar = NULL;
354
355 /* Determine how to handle the ordering of options and nonoptions. */
356
357 if (optstring[0] == '-')
358 {
359 ordering = RETURN_IN_ORDER;
360 ++optstring;
361 }
362 else if (optstring[0] == '+')
363 {
364 ordering = REQUIRE_ORDER;
365 ++optstring;
366 }
367 else if (getenv ("POSIXLY_CORRECT") != NULL)
368 ordering = REQUIRE_ORDER;
369 else
370 ordering = PERMUTE;
371 }
372
373 if (nextchar == NULL || *nextchar == '\0')
374 {
375 if (ordering == PERMUTE)
376 {
377 /* If we have just processed some options following some non-options,
378 exchange them so that the options come first. */
379
380 if (first_nonopt != last_nonopt && last_nonopt != optind)
381 exchange ((char **) argv);
382 else if (last_nonopt != optind)
383 first_nonopt = optind;
384
385 /* Now skip any additional non-options
386 and extend the range of non-options previously skipped. */
387
388 while (optind < argc
389 && (argv[optind][0] != '-' || argv[optind][1] == '\0')
390#ifdef GETOPT_COMPAT
391 && (longopts == NULL
392 || argv[optind][0] != '+' || argv[optind][1] == '\0')
393#endif /* GETOPT_COMPAT */
394 )
395 optind++;
396 last_nonopt = optind;
397 }
398
399 /* Special ARGV-element `--' means premature end of options.
400 Skip it like a null option,
401 then exchange with previous non-options as if it were an option,
402 then skip everything else like a non-option. */
403
404 if (optind != argc && !strcmp (argv[optind], "--"))
405 {
406 optind++;
407
408 if (first_nonopt != last_nonopt && last_nonopt != optind)
409 exchange ((char **) argv);
410 else if (first_nonopt == last_nonopt)
411 first_nonopt = optind;
412 last_nonopt = argc;
413
414 optind = argc;
415 }
416
417 /* If we have done all the ARGV-elements, stop the scan
418 and back over any non-options that we skipped and permuted. */
419
420 if (optind == argc)
421 {
422 /* Set the next-arg-index to point at the non-options
423 that we previously skipped, so the caller will digest them. */
424 if (first_nonopt != last_nonopt)
425 optind = first_nonopt;
426 return EOF;
427 }
428
429 /* If we have come to a non-option and did not permute it,
430 either stop the scan or describe it to the caller and pass it by. */
431
432 if ((argv[optind][0] != '-' || argv[optind][1] == '\0')
433#ifdef GETOPT_COMPAT
434 && (longopts == NULL
435 || argv[optind][0] != '+' || argv[optind][1] == '\0')
436#endif /* GETOPT_COMPAT */
437 )
438 {
439 if (ordering == REQUIRE_ORDER)
440 return EOF;
441 optarg = argv[optind++];
442 return 1;
443 }
444
445 /* We have found another option-ARGV-element.
446 Start decoding its characters. */
447
448 nextchar = (argv[optind] + 1
449 + (longopts != NULL && argv[optind][1] == '-'));
450 }
451
452 if (longopts != NULL
453 && ((argv[optind][0] == '-'
454 && (argv[optind][1] == '-' || long_only))
455#ifdef GETOPT_COMPAT
456 || argv[optind][0] == '+'
457#endif /* GETOPT_COMPAT */
458 ))
459 {
460 const struct option *p;
461 char *s = nextchar;
462 int exact = 0;
463 int ambig = 0;
464 const struct option *pfound = NULL;
465 int indfound;
466
467 while (*s && *s != '=')
468 s++;
469
470 /* Test all options for either exact match or abbreviated matches. */
471 for (p = longopts, option_index = 0; p->name;
472 p++, option_index++)
473 if (!strncmp (p->name, nextchar, s - nextchar))
474 {
475 if (s - nextchar == strlen (p->name))
476 {
477 /* Exact match found. */
478 pfound = p;
479 indfound = option_index;
480 exact = 1;
481 break;
482 }
483 else if (pfound == NULL)
484 {
485 /* First nonexact match found. */
486 pfound = p;
487 indfound = option_index;
488 }
489 else
490 /* Second nonexact match found. */
491 ambig = 1;
492 }
493
494 if (ambig && !exact)
495 {
496 if (opterr)
497 fprintf (stderr, "%s: option `%s' is ambiguous\n",
498 argv[0], argv[optind]);
499 nextchar += strlen (nextchar);
500 optind++;
501 return '?';
502 }
503
504 if (pfound != NULL)
505 {
506 option_index = indfound;
507 optind++;
508 if (*s)
509 {
510 /* Don't test has_arg with >, because some C compilers don't
511 allow it to be used on enums. */
512 if (pfound->has_arg)
513 optarg = s + 1;
514 else
515 {
516 if (opterr)
517 {
518 if (argv[optind - 1][1] == '-')
519 /* --option */
520 fprintf (stderr,
521 "%s: option `--%s' doesn't allow an argument\n",
522 argv[0], pfound->name);
523 else
524 /* +option or -option */
525 fprintf (stderr,
526 "%s: option `%c%s' doesn't allow an argument\n",
527 argv[0], argv[optind - 1][0], pfound->name);
528 }
529 nextchar += strlen (nextchar);
530 return '?';
531 }
532 }
533 else if (pfound->has_arg == 1)
534 {
535 if (optind < argc)
536 optarg = argv[optind++];
537 else
538 {
539 if (opterr)
540 fprintf (stderr, "%s: option `%s' requires an argument\n",
541 argv[0], argv[optind - 1]);
542 nextchar += strlen (nextchar);
543 return optstring[0] == ':' ? ':' : '?';
544 }
545 }
546 nextchar += strlen (nextchar);
547 if (longind != NULL)
548 *longind = option_index;
549 if (pfound->flag)
550 {
551 *(pfound->flag) = pfound->val;
552 return 0;
553 }
554 return pfound->val;
555 }
556 /* Can't find it as a long option. If this is not getopt_long_only,
557 or the option starts with '--' or is not a valid short
558 option, then it's an error.
559 Otherwise interpret it as a short option. */
560 if (!long_only || argv[optind][1] == '-'
561#ifdef GETOPT_COMPAT
562 || argv[optind][0] == '+'
563#endif /* GETOPT_COMPAT */
564 || my_index (optstring, *nextchar) == NULL)
565 {
566 if (opterr)
567 {
568 if (argv[optind][1] == '-')
569 /* --option */
570 fprintf (stderr, "%s: unrecognized option `--%s'\n",
571 argv[0], nextchar);
572 else
573 /* +option or -option */
574 fprintf (stderr, "%s: unrecognized option `%c%s'\n",
575 argv[0], argv[optind][0], nextchar);
576 }
577 nextchar = (char *) "";
578 optind++;
579 return '?';
580 }
581 }
582
583 /* Look at and handle the next option-character. */
584
585 {
586 char c = *nextchar++;
587 char *temp = my_index (optstring, c);
588
589 /* Increment `optind' when we start to process its last character. */
590 if (*nextchar == '\0')
591 ++optind;
592
593 if (temp == NULL || c == ':')
594 {
595 if (opterr)
596 {
597#if 0
598 if (c < 040 || c >= 0177)
599 fprintf (stderr, "%s: unrecognized option, character code 0%o\n",
600 argv[0], c);
601 else
602 fprintf (stderr, "%s: unrecognized option `-%c'\n", argv[0], c);
603#else
604 /* 1003.2 specifies the format of this message. */
605 fprintf (stderr, "%s: illegal option -- %c\n", argv[0], c);
606#endif
607 }
608 optopt = c;
609 return '?';
610 }
611 if (temp[1] == ':')
612 {
613 if (temp[2] == ':')
614 {
615 /* This is an option that accepts an argument optionally. */
616 if (*nextchar != '\0')
617 {
618 optarg = nextchar;
619 optind++;
620 }
621 else
622 optarg = 0;
623 nextchar = NULL;
624 }
625 else
626 {
627 /* This is an option that requires an argument. */
628 if (*nextchar != '\0')
629 {
630 optarg = nextchar;
631 /* If we end this ARGV-element by taking the rest as an arg,
632 we must advance to the next element now. */
633 optind++;
634 }
635 else if (optind == argc)
636 {
637 if (opterr)
638 {
639#if 0
640 fprintf (stderr, "%s: option `-%c' requires an argument\n",
641 argv[0], c);
642#else
643 /* 1003.2 specifies the format of this message. */
644 fprintf (stderr, "%s: option requires an argument -- %c\n",
645 argv[0], c);
646#endif
647 }
648 optopt = c;
649 if (optstring[0] == ':')
650 c = ':';
651 else
652 c = '?';
653 }
654 else
655 /* We already incremented `optind' once;
656 increment it again when taking next ARGV-elt as argument. */
657 optarg = argv[optind++];
658 nextchar = NULL;
659 }
660 }
661 return c;
662 }
663}
664
665int
666getopt (argc, argv, optstring)
667 int argc;
668 char *const *argv;
669 const char *optstring;
670{
671 return _getopt_internal (argc, argv, optstring,
672 (const struct option *) 0,
673 (int *) 0,
674 0);
675}
676
677#endif /* _LIBC or not __GNU_LIBRARY__. */
678
679
680#ifdef TEST
681
682/* Compile with -DTEST to make an executable for use in testing
683 the above definition of `getopt'. */
684
685int
686main (argc, argv)
687 int argc;
688 char **argv;
689{
690 int c;
691 int digit_optind = 0;
692
693 while (1)
694 {
695 int this_option_optind = optind ? optind : 1;
696
697 c = getopt (argc, argv, "abc:d:0123456789");
698 if (c == EOF)
699 break;
700
701 switch (c)
702 {
703 case '0':
704 case '1':
705 case '2':
706 case '3':
707 case '4':
708 case '5':
709 case '6':
710 case '7':
711 case '8':
712 case '9':
713 if (digit_optind != 0 && digit_optind != this_option_optind)
714 printf ("digits occur in two different argv-elements.\n");
715 digit_optind = this_option_optind;
716 printf ("option %c\n", c);
717 break;
718
719 case 'a':
720 printf ("option a\n");
721 break;
722
723 case 'b':
724 printf ("option b\n");
725 break;
726
727 case 'c':
728 printf ("option c with value `%s'\n", optarg);
729 break;
730
731 case '?':
732 break;
733
734 default:
735 printf ("?? getopt returned character code 0%o ??\n", c);
736 }
737 }
738
739 if (optind < argc)
740 {
741 printf ("non-option ARGV-elements: ");
742 while (optind < argc)
743 printf ("%s ", argv[optind++]);
744 printf ("\n");
745 }
746
747 exit (0);
748}
749
750#endif /* TEST */
Note: See TracBrowser for help on using the repository browser.