8 #include "stdio_impl.h"
10 extern int __optpos
, __optreset
;
12 static void permute(char *const *argv
, int dest
, int src
)
14 char **av
= (char **)argv
;
17 for (i
=src
; i
>dest
; i
--)
22 static int __getopt_long_core(int argc
, char *const *argv
, const char *optstring
, const struct option
*longopts
, int *idx
, int longonly
);
24 static int __getopt_long(int argc
, char *const *argv
, const char *optstring
, const struct option
*longopts
, int *idx
, int longonly
)
26 int ret
, skipped
, resumed
;
27 if (!optind
|| __optreset
) {
32 if (optind
>= argc
|| !argv
[optind
]) return -1;
34 if (optstring
[0] != '+' && optstring
[0] != '-') {
36 for (i
=optind
; ; i
++) {
37 if (i
>= argc
|| !argv
[i
]) return -1;
38 if (argv
[i
][0] == '-' && argv
[i
][1]) break;
43 ret
= __getopt_long_core(argc
, argv
, optstring
, longopts
, idx
, longonly
);
44 if (resumed
> skipped
) {
45 int i
, cnt
= optind
-resumed
;
47 permute(argv
, skipped
, optind
-1);
48 optind
= skipped
+ cnt
;
53 static int __getopt_long_core(int argc
, char *const *argv
, const char *optstring
, const struct option
*longopts
, int *idx
, int longonly
)
56 if (longopts
&& argv
[optind
][0] == '-' &&
57 ((longonly
&& argv
[optind
][1] && argv
[optind
][1] != '-') ||
58 (argv
[optind
][1] == '-' && argv
[optind
][2])))
60 int colon
= optstring
[optstring
[0]=='+'||optstring
[0]=='-']==':';
62 char *arg
, *opt
, *start
= argv
[optind
]+1;
63 for (cnt
=i
=0; longopts
[i
].name
; i
++) {
64 const char *name
= longopts
[i
].name
;
66 if (*opt
== '-') opt
++;
67 while (*opt
&& *opt
!= '=' && *opt
== *name
)
69 if (*opt
&& *opt
!= '=') continue;
78 if (cnt
==1 && longonly
&& arg
-start
== mblen(start
, MB_LEN_MAX
)) {
80 for (i
=0; optstring
[i
]; i
++) {
82 for (j
=0; j
<l
&& start
[j
]==optstring
[i
+j
]; j
++);
94 if (!longopts
[i
].has_arg
) {
95 optopt
= longopts
[i
].val
;
99 ": option does not take an argument: ",
101 strlen(longopts
[i
].name
));
105 } else if (longopts
[i
].has_arg
== required_argument
) {
106 if (!(optarg
= argv
[optind
])) {
107 optopt
= longopts
[i
].val
;
108 if (colon
) return ':';
109 if (!opterr
) return '?';
110 __getopt_msg(argv
[0],
111 ": option requires an argument: ",
113 strlen(longopts
[i
].name
));
119 if (longopts
[i
].flag
) {
120 *longopts
[i
].flag
= longopts
[i
].val
;
123 return longopts
[i
].val
;
125 if (argv
[optind
][1] == '-') {
127 if (!colon
&& opterr
)
128 __getopt_msg(argv
[0], cnt
?
129 ": option is ambiguous: " :
130 ": unrecognized option: ",
132 strlen(argv
[optind
]+2));
137 return getopt(argc
, argv
, optstring
);
140 int getopt_long(int argc
, char *const *argv
, const char *optstring
, const struct option
*longopts
, int *idx
)
142 return __getopt_long(argc
, argv
, optstring
, longopts
, idx
, 0);
145 int getopt_long_only(int argc
, char *const *argv
, const char *optstring
, const struct option
*longopts
, int *idx
)
147 return __getopt_long(argc
, argv
, optstring
, longopts
, idx
, 1);