xref: /minix3/minix/commands/cawf/getopt.c (revision d0055759dd8892194db7fce6acc5085d5c9aeaee)
1 #ifndef __minix
2 /*
3 Newsgroups: mod.std.unix
4 Subject: public domain AT&T getopt source
5 Date: 3 Nov 85 19:34:15 GMT
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 
14 
15 /*LINTLIBRARY*/
16 #define NULL	0
17 #define EOF	(-1)
18 #define ERR(s, c)	if(opterr){\
19 	extern int strlen(), write();\
20 	char errbuf[2];\
21 	errbuf[0] = c; errbuf[1] = '\n';\
22 	(void) write(2, argv[0], (unsigned)strlen(argv[0]));\
23 	(void) write(2, s, (unsigned)strlen(s));\
24 	(void) write(2, errbuf, 2);}
25 
26 extern int strcmp();
27 extern char *strchr();
28 
29 int	opterr = 1;
30 int	optind = 1;
31 int	optopt;
32 char	*optarg;
33 
getopt(int argc,char ** argv,char ** opts)34 int getopt(int argc, char **argv, char **opts) {
35 	static int sp = 1;
36 	register int c;
37 	register char *cp;
38 
39 	if(sp == 1)
40 		if(optind >= argc ||
41 		   argv[optind][0] != '-' || argv[optind][1] == '\0')
42 			return(EOF);
43 		else if(strcmp(argv[optind], "--") == NULL) {
44 			optind++;
45 			return(EOF);
46 		}
47 	optopt = c = argv[optind][sp];
48 	if(c == ':' || (cp=strchr(opts, c)) == NULL) {
49 		ERR(": illegal option -- ", c);
50 		if(argv[optind][++sp] == '\0') {
51 			optind++;
52 			sp = 1;
53 		}
54 		return('?');
55 	}
56 	if(*++cp == ':') {
57 		if(argv[optind][sp+1] != '\0')
58 			optarg = &argv[optind++][sp+1];
59 		else if(++optind >= argc) {
60 			ERR(": option requires an argument -- ", c);
61 			sp = 1;
62 			return('?');
63 		} else
64 			optarg = argv[optind++];
65 		sp = 1;
66 	} else {
67 		if(argv[optind][++sp] == '\0') {
68 			sp = 1;
69 			optind++;
70 		}
71 		optarg = NULL;
72 	}
73 	return(c);
74 }
75 #endif /* !__minix */
76