2
Date: Tue, 25 Dec 84 19:20:50 EST
3
From: Keith Bostic <harvard!seismo!keith>
5
Subject: public domain getopt(3)
7
There have recently been several requests for a public
8
domain version of getopt(3), recently. Thought this
9
might be worth reposting.
15
======================================================================
16
In April of this year, Henry Spencer (utzoo!henry) released a public
17
domain version of getopt (USG, getopt(3)). Well, I've been trying to
18
port some USG dependent software and it didn't seem to work. The problem
19
ended up being that the USG version of getopt has some external variables
20
that aren't mentioned in the documentation. Anyway, to fix these problems,
21
I rewrote the public version of getopt. It has the following advantages:
23
-- it includes those "unknown" variables
24
-- it's smaller/faster 'cause it doesn't use the formatted
25
output conversion routines in section 3 of the UNIX manual.
26
-- the error messages are the same as S5's.
27
-- it has the same side-effects that S5's has.
28
-- the posted bug on how the error messages are flushed has been
29
implemented. (posting by Tony Hansen; pegasus!hansen)
31
I won't post the man pages since Henry already did; a special note,
32
it's not documented in the S5 manual that the options ':' and '?' are
33
illegal. It should be obvious, but I thought I'd mention it...
34
This software was derived from binaries of S5 and the S5 man page, and is
35
(I think?) totally (I'm pretty sure?) compatible with S5 and backward
36
compatible to Henry's version.
42
*UNIX is a trademark of Bell Laboratories
44
.. cut along the dotted line .........................................
55
* get option letter from argument vector
57
int optind = 1, /* index into parent argv vector */
58
optopt; /* character checked for validity */
59
char *optarg; /* argument associated with option */
61
#define BADCH (int)'?'
63
#define tell(s) fputs(*nargv,stderr);fputs(s,stderr); \
64
fputc(optopt,stderr);fputc('\n',stderr);return(BADCH);
66
int getopt(int nargc, char **nargv, char *ostr)
68
static char *place = EMSG; /* option letter processing */
69
static char *lastostr = (char *) 0;
70
register char *oli; /* option letter list index */
72
/* LANCE PATCH: dynamic reinitialization */
73
if (ostr != lastostr) {
77
if(!*place) { /* update scanning pointer */
78
if((optind >= nargc) || (*(place = nargv[optind]) != '-')
83
if (*place == '-') { /* found "--" */
87
} /* option letter okay? */
88
if ((optopt = (int)*place++) == (int)':' || !(oli = strchr(ostr,optopt))) {
90
tell(": illegal option -- ");
92
if (*++oli != ':') { /* don't need argument */
94
if (!*place) ++optind;
96
else { /* need an argument */
97
if (*place) optarg = place; /* no white space */
98
else if (nargc <= ++optind) { /* no arg */
100
tell(": option requires an argument -- ");
102
else optarg = nargv[optind]; /* white space */
106
return(optopt); /* dump back option letter */