diff options
Diffstat (limited to 'subgetopt.c')
-rw-r--r-- | subgetopt.c | 67 |
1 files changed, 67 insertions, 0 deletions
diff --git a/subgetopt.c b/subgetopt.c new file mode 100644 index 0000000..85ace96 --- /dev/null +++ b/subgetopt.c | |||
@@ -0,0 +1,67 @@ | |||
1 | /* Public domain. */ | ||
2 | |||
3 | #define SUBGETOPTNOSHORT | ||
4 | #include "subgetopt.h" | ||
5 | |||
6 | #define sgopt subgetopt | ||
7 | #define optind subgetoptind | ||
8 | #define optpos subgetoptpos | ||
9 | #define optarg subgetoptarg | ||
10 | #define optproblem subgetoptproblem | ||
11 | #define optdone subgetoptdone | ||
12 | |||
13 | int optind = 1; | ||
14 | int optpos = 0; | ||
15 | const char *optarg = 0; | ||
16 | int optproblem = 0; | ||
17 | int optdone = SUBGETOPTDONE; | ||
18 | |||
19 | int sgopt(int argc,const char *const *argv,const char *opts) | ||
20 | { | ||
21 | int c; | ||
22 | const char *s; | ||
23 | |||
24 | optarg = 0; | ||
25 | if (!argv || (optind >= argc) || !argv[optind]) return optdone; | ||
26 | if (optpos && !argv[optind][optpos]) { | ||
27 | ++optind; | ||
28 | optpos = 0; | ||
29 | if ((optind >= argc) || !argv[optind]) return optdone; | ||
30 | } | ||
31 | if (!optpos) { | ||
32 | if (argv[optind][0] != '-') return optdone; | ||
33 | ++optpos; | ||
34 | c = argv[optind][1]; | ||
35 | if ((c == '-') || (c == 0)) { | ||
36 | if (c) ++optind; | ||
37 | optpos = 0; | ||
38 | return optdone; | ||
39 | } | ||
40 | /* otherwise c is reassigned below */ | ||
41 | } | ||
42 | c = argv[optind][optpos]; | ||
43 | ++optpos; | ||
44 | s = opts; | ||
45 | while (*s) { | ||
46 | if (c == *s) { | ||
47 | if (s[1] == ':') { | ||
48 | optarg = argv[optind] + optpos; | ||
49 | ++optind; | ||
50 | optpos = 0; | ||
51 | if (!*optarg) { | ||
52 | optarg = argv[optind]; | ||
53 | if ((optind >= argc) || !optarg) { /* argument past end */ | ||
54 | optproblem = c; | ||
55 | return '?'; | ||
56 | } | ||
57 | ++optind; | ||
58 | } | ||
59 | } | ||
60 | return c; | ||
61 | } | ||
62 | ++s; | ||
63 | if (*s == ':') ++s; | ||
64 | } | ||
65 | optproblem = c; | ||
66 | return '?'; | ||
67 | } | ||