add getopt reset support
authorRich Felker <dalias@aerifal.cx>
Mon, 1 Oct 2012 00:00:38 +0000 (20:00 -0400)
committerRich Felker <dalias@aerifal.cx>
Mon, 1 Oct 2012 00:00:38 +0000 (20:00 -0400)
based on proposed patches by Daniel Cegiełka, with minor changes:
- use a weak symbol for optreset so it doesn't clash with namespace
- also reset optpos (position in multi-option arg like -lR)
- also make getopt_long support reset

include/getopt.h
src/misc/getopt.c
src/misc/getopt_long.c

index 6d85c0b..c1d0df9 100644 (file)
@@ -7,7 +7,7 @@ extern "C" {
 
 int getopt(int, char * const [], const char *);
 extern char *optarg;
-extern int optind, opterr, optopt;
+extern int optind, opterr, optopt, optreset;
 
 struct option
 {
index abf0e84..35880a0 100644 (file)
@@ -3,10 +3,13 @@
 #include <string.h>
 #include <limits.h>
 #include <stdlib.h>
+#include "libc.h"
 
 char *optarg;
-int optind=1, opterr=1, optopt;
-static int optpos;
+int optind=1, opterr=1, optopt, __optpos, __optreset=0;
+
+#define optpos __optpos
+weak_alias(__optreset, optreset);
 
 int getopt(int argc, char * const argv[], const char *optstring)
 {
@@ -15,6 +18,12 @@ int getopt(int argc, char * const argv[], const char *optstring)
        int k, l;
        char *optchar;
 
+       if (!optind || __optreset) {
+               __optreset = 0;
+               __optpos = 0;
+               optind = 1;
+       }
+
        if (optind >= argc || !argv[optind] || argv[optind][0] != '-' || !argv[optind][1])
                return -1;
        if (argv[optind][1] == '-' && !argv[optind][2])
index 6d3a4a6..4ef5a5c 100644 (file)
@@ -3,8 +3,15 @@
 #include <getopt.h>
 #include <stdio.h>
 
+extern int __optpos, __optreset;
+
 static int __getopt_long(int argc, char *const *argv, const char *optstring, const struct option *longopts, int *idx, int longonly)
 {
+       if (!optind || __optreset) {
+               __optreset = 0;
+               __optpos = 0;
+               optind = 1;
+       }
        if (optind >= argc || !argv[optind] || argv[optind][0] != '-') return -1;
        if ((longonly && argv[optind][1]) ||
                (argv[optind][1] == '-' && argv[optind][2]))