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