xref: /plan9/sys/src/cmd/postscript/common/getopt.c (revision 219b2ee8daee37f4aad58d63f21287faa8e4ffdc)
1 #ifndef _POSIX_SOURCE
2 #include <u.h>
3 #include <libc.h>
4 #endif
5 #include	<stdio.h>
6 #define ERR(str, chr)       if(opterr){fprintf(stderr, "%s%s%c\n", argv[0], str, chr);}
7 int     opterr = 1;
8 int     optind = 1;
9 int	optopt;
10 char    *optarg;
11 char    *strchr();
12 
13 int
14 getopt (argc, argv, opts)
15 char **argv, *opts;
16 {
17 	static int sp = 1;
18 	register c;
19 	register char *cp;
20 
21 	if (sp == 1)
22 		if (optind >= argc ||
23 		   argv[optind][0] != '-' || argv[optind][1] == '\0')
24 			return EOF;
25 		else if (strcmp(argv[optind], "--") == NULL) {
26 			optind++;
27 			return EOF;
28 		}
29 	optopt = c = argv[optind][sp];
30 	if (c == ':' || (cp=strchr(opts, c)) == NULL) {
31 		ERR (": illegal option -- ", c);
32 		if (argv[optind][++sp] == '\0') {
33 			optind++;
34 			sp = 1;
35 		}
36 		return '?';
37 	}
38 	if (*++cp == ':') {
39 		if (argv[optind][sp+1] != '\0')
40 			optarg = &argv[optind++][sp+1];
41 		else if (++optind >= argc) {
42 			ERR (": option requires an argument -- ", c);
43 			sp = 1;
44 			return '?';
45 		} else
46 			optarg = argv[optind++];
47 		sp = 1;
48 	} else {
49 		if (argv[optind][++sp] == '\0') {
50 			sp = 1;
51 			optind++;
52 		}
53 		optarg = NULL;
54 	}
55 	return c;
56 }
57