2 I got this off net.sources from Henry Spencer.
3 It is a public domain getopt(3) like in System V.
4 I have made the following modifications:
6 index(s,c) was added because too many people could
7 not compile getopt without it.
9 A test main program was added, ifdeffed by GETOPT.
10 This main program is a public domain implementation
11 of the getopt(1) program like in System V. The getopt
12 program can be used to standardize shell option handling.
13 e.g. cc -DGETOPT getopt.c -o getopt
18 static char sccsfid[] = "@(#) getopt.c 5.0 (UTZoo) 1985";
21 #define ARGCH (int)':'
22 #define BADCH (int)'?'
26 /* this is included because index is not on some UNIX systems */
34 if (c == *s) return (s);
40 * get option letter from argument vector
42 int opterr = 1, /* useless, never set or used */
43 optind = 1, /* index into parent argv vector */
44 optopt; /* character checked for validity */
45 char *optarg; /* argument associated with option */
47 #define tell(s) fputs(*nargv,stderr);fputs(s,stderr); \
48 fputc(optopt,stderr);fputc('\n',stderr);return(BADCH);
51 getopt(nargc,nargv,ostr)
56 static char *place = EMSG; /* option letter processing */
57 register char *oli; /* option letter list index */
60 if(!*place) { /* update scanning pointer */
61 if(optind >= nargc || *(place = nargv[optind]) != '-' || !*++place) return(EOF);
62 if (*place == '-') { /* found "--" */
66 } /* option letter okay? */
67 if ((optopt = (int)*place++) == ARGCH || !(oli = index(ostr,optopt))) {
69 tell(": illegal option -- ");
71 if (*++oli != ARGCH) { /* don't need argument */
73 if (!*place) ++optind;
75 else { /* need an argument */
76 if (*place) optarg = place; /* no white space */
77 else if (nargc <= ++optind) { /* no arg */
79 tell(": option requires an argument -- ");
81 else optarg = nargv[optind]; /* white space */
85 return(optopt); /* dump back option letter */
92 static char sccspid[] = "@(#) getopt.c 5.1 (WangInst) 6/15/85";
95 main (argc, argv) char **argv;
97 char *optstring = argv[1];
98 char *argv0 = argv[0];
106 fprintf (stderr, "Usage: %s optstring args\n", argv0);
112 while ((C = getopt (argc, argv, optstring)) != EOF)
114 if (C == BADCH) opterr++;
116 opi = index (optstring, C);
117 if (opi && opi[1] == ARGCH)
119 printf ("\"%s\" ", optarg);
122 printf ("%s", ENDARGS);
123 while (optind < argc)
124 printf (" \"%s\"", argv[optind++]);