2 * Copyright (C) 2006 Rich Felker <dalias@aerifal.cx>
4 * Licensed under the LGPL v2.1, see the file COPYING.LIB in this tarball.
12 static int __getopt_long(int argc
, char *const *argv
, const char *optstring
, const struct option
*longopts
, int *idx
, int longonly
)
14 if (optind
>= argc
|| !argv
[optind
] || argv
[optind
][0] != '-') return -1;
15 if ((longonly
&& argv
[optind
][1]) ||
16 (argv
[optind
][1] == '-' && argv
[optind
][2]))
19 for (i
=0; longopts
[i
].name
; i
++) {
20 const char *name
= longopts
[i
].name
;
21 char *opt
= argv
[optind
]+2;
22 while (*name
&& *name
++ == *opt
++);
23 if (*name
|| (*opt
&& *opt
!= '=')) continue;
25 if (!longopts
[i
].has_arg
) continue;
28 if (longopts
[i
].has_arg
== required_argument
) {
29 if (!(optarg
= argv
[++optind
]))
35 if (longopts
[i
].flag
) {
36 *longopts
[i
].flag
= longopts
[i
].val
;
39 return longopts
[i
].val
;
41 if (argv
[optind
][1] == '-') {
46 return getopt(argc
, argv
, optstring
);
49 int getopt_long(int argc
, char *const *argv
, const char *optstring
, const struct option
*longopts
, int *idx
)
51 return __getopt_long(argc
, argv
, optstring
, longopts
, idx
, 0);
54 int getopt_long_only(int argc
, char *const *argv
, const char *optstring
, const struct option
*longopts
, int *idx
)
56 return __getopt_long(argc
, argv
, optstring
, longopts
, idx
, 1);