-
Notifications
You must be signed in to change notification settings - Fork 1
/
getopt.c
101 lines (88 loc) · 1.88 KB
/
getopt.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/* (c) 2006, Quest Software, Inc. All rights reserved. */
/* David Leonard, 2006 */
#if HAVE_CONFIG_H
# include <config.h>
#endif
#if STDC_HEADERS
# include <stdio.h>
#endif
/*
* Simple getopt implementation, for platforms without it.
*/
char *optarg;
int optind = 1, opterr = 1, optopt;
int optidx = 0;
int
getopt(int argc, char * const argv[], const char *optstring)
{
const char *p;
char ch;
if (argv[optind] == NULL || *argv[optind] != '-' || !argv[optind][1])
return -1;
ch = argv[optind][optidx + 1];
if (ch == '-' && optidx == 0 && !argv[optind][2]) {
optind++;
optidx = 0;
return -1;
}
p = optstring;
if (*p == ':')
p++;
while (*p) {
if (*p == ch)
break;
p++;
if (*p == ':')
p++;
}
if (!*p) {
optopt = ch;
if (*optstring != ':')
fprintf(stderr, "unknown option -%c\n", ch);
if (argv[optind][optidx + 2] == '\0') {
optind++;
optidx = 0;
} else
optidx++;
return '?';
}
if (p[1] == ':') {
if (argv[optind][optidx + 2])
optarg = argv[optind] + optidx + 2;
else {
optarg = argv[++optind];
if (!optarg) {
if (*optstring != ':')
fprintf(stderr, "missing argument to -%c\n", *p);
optopt = *p;
return ':';
}
}
optind++;
optidx = 0;
} else if (argv[optind][optidx + 2] == '\0') {
optind++;
optidx = 0;
} else
optidx++;
return *p;
}
#if TEST
int
main(int argc, char **argv)
{
int ch;
while ((ch = getopt(argc, argv, "ab:c:")) != -1)
switch (ch) {
case 'a': printf("got -a\n"); break;
case 'b': printf("got -b optarg=%s\n", optarg); break;
case 'c': printf("got -c optarg=%s\n", optarg);
printf(" 2nd arg: %s\n", argv[optind++]);
break;
default: printf("error '%c' optopt=%c\n", ch, optopt);
}
while (optind < argc)
printf("extra arg: %s\n", argv[optind++]);
exit(0);
}
#endif