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