Skip to content

Commit 3706821

Browse files
committed
mygetopt: add optreset
1 parent 40ee963 commit 3706821

File tree

2 files changed

+9
-4
lines changed

2 files changed

+9
-4
lines changed

util/mygetopt.c

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
#include "mygetopt.h"
3131

3232
/* Supported extensions:
33+
* resetting the state by optind=0 (GNU) or optreset=1 (BSD)
3334
* "::" in optstring for optional arguments
3435
*/
3536

@@ -129,7 +130,7 @@ static void getopt_parse_optstring(struct getopt_state *s, const char *optstring
129130
}
130131

131132
char *optarg = NULL;
132-
int opterr = 1, optind = 1, optopt = 0;
133+
int opterr = 1, optind = 1, optopt = 0, optreset = 0;
133134
static struct getopt_state getopt_g_state = {0};
134135
int getopt(int argc, char *const argv[], const char *optstring)
135136
{
@@ -140,11 +141,15 @@ int getopt(int argc, char *const argv[], const char *optstring)
140141
s->ind = optind;
141142
s->argc = argc;
142143
s->argv = argv;
143-
if (s->string != optstring || !optind)
144-
getopt_parse_optstring(s, optstring);
145144
if (!optind) {
146145
s->ind = 1;
146+
optreset = 1;
147+
}
148+
if (s->string != optstring || optreset)
149+
getopt_parse_optstring(s, optstring);
150+
if (optreset) {
147151
s->next = 0;
152+
optreset = 0;
148153
}
149154
rv = getopt_internal(s);
150155
optarg = s->arg;

util/mygetopt.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,6 @@
3131
#define util_optopt optopt
3232
#define util_getopt getopt
3333
extern char *optarg;
34-
extern int opterr, optind, optopt;
34+
extern int opterr, optind, optopt, optreset;
3535
int getopt(int argc, char *const argv[], const char *optstring);
3636
#endif

0 commit comments

Comments
 (0)