1 #ifdef HAVE_STDLIB_H
2 #include <stdlib.h>
3 #endif
4
5 /*
6 * Here's something you've all been waiting for: the AT&T public domain
7 * source for getopt(3). It is the code which was given out at the 1985
8 * UNIFORUM conference in Dallas. I obtained it by electronic mail
9 * directly from AT&T. The people there assure me that it is indeed
10 * in the public domain.
11 *
12 * There is no manual page. That is because the one they gave out at
13 * UNIFORUM was slightly different from the current System V Release 2
14 * manual page. The difference apparently involved a note about the
15 * famous rules 5 and 6, recommending using white space between an option
16 * and its first argument, and not grouping options that have arguments.
17 * Getopt itself is currently lenient about both of these things White
18 * space is allowed, but not mandatory, and the last option in a group can
19 * have an argument. That particular version of the man page evidently
20 * has no official existence, and my source at AT&T did not send a copy.
21 * The current SVR2 man page reflects the actual behavor of this getopt.
22 * However, I am not about to post a copy of anything licensed by AT&T.
23 */
24
25 #include <stdio.h>
26 #include <strings.h>
27 #include <string.h>
28
29 /*LINTLIBRARY*/
30 #ifndef NULL
31 #define NULL 0
32 #endif
33 #define EOF (-1)
34
35
36 int opterr = 1;
37 int optind = 1;
38 int optopt;
39 char *optarg;
40
ERR(char * s,char c,char ** argv)41 void ERR(char *s, char c, char **argv)
42 {
43 if(opterr)
44 {
45 char errbuf[2];
46 errbuf[0] = c;
47 errbuf[1] = '\n';
48 /* (void) write(2, argv[0], (unsigned)strlen(argv[0]));
49 (void) write(2, s, (unsigned)strlen(s));
50 (void) write(2, errbuf, 2); */
51 (void) fwrite(argv[0], (unsigned)strlen(argv[0]),1,stderr);
52 (void) fwrite(s, (unsigned)strlen(s),1,stderr);
53 (void) fwrite(errbuf, 2, 1,stderr);
54 }
55 }
56
index2(char * str,char c)57 char *index2(char *str, char c)
58 {
59 char *ret;
60 ret=strchr(str,c);
61 return(ret);
62 }
63
64
getoptions(int argc,char ** argv,char * opts)65 int getoptions(int argc, char **argv, char *opts)
66 {
67 static int sp = 1;
68 register int c;
69 register char *cp;
70
71 if(sp == 1)
72 if(optind >= argc ||
73 argv[optind][0] != '-' || argv[optind][1] == '\0')
74 return(EOF);
75 else if(strcmp(argv[optind], "--") == 0) {
76 optind++;
77 return(EOF);
78 }
79 optopt = c = argv[optind][sp];
80 if(c == ':' || (cp=index2(opts, c)) == NULL) {
81 ERR(": illegal option -- ", c,argv);
82 if(argv[optind][++sp] == '\0') {
83 optind++;
84 sp = 1;
85 }
86 return('?');
87 }
88 if(*++cp == ':') {
89 if(argv[optind][sp+1] != '\0')
90 optarg = &argv[optind++][sp+1];
91 else if(++optind >= argc) {
92 ERR(": option requires an argument -- ", c,argv);
93 sp = 1;
94 return('?');
95 } else
96 optarg = argv[optind++];
97 sp = 1;
98 } else {
99 if(argv[optind][++sp] == '\0') {
100 sp = 1;
101 optind++;
102 }
103 optarg = NULL;
104 }
105 return(c);
106 }
107