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