提交 030e5263 编写于 作者: R Rich Felker

add getopt reset support

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
上级 e44849f5
...@@ -7,7 +7,7 @@ extern "C" { ...@@ -7,7 +7,7 @@ extern "C" {
int getopt(int, char * const [], const char *); int getopt(int, char * const [], const char *);
extern char *optarg; extern char *optarg;
extern int optind, opterr, optopt; extern int optind, opterr, optopt, optreset;
struct option struct option
{ {
......
...@@ -3,10 +3,13 @@ ...@@ -3,10 +3,13 @@
#include <string.h> #include <string.h>
#include <limits.h> #include <limits.h>
#include <stdlib.h> #include <stdlib.h>
#include "libc.h"
char *optarg; char *optarg;
int optind=1, opterr=1, optopt; int optind=1, opterr=1, optopt, __optpos, __optreset=0;
static int optpos;
#define optpos __optpos
weak_alias(__optreset, optreset);
int getopt(int argc, char * const argv[], const char *optstring) int getopt(int argc, char * const argv[], const char *optstring)
{ {
...@@ -15,6 +18,12 @@ 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; int k, l;
char *optchar; char *optchar;
if (!optind || __optreset) {
__optreset = 0;
__optpos = 0;
optind = 1;
}
if (optind >= argc || !argv[optind] || argv[optind][0] != '-' || !argv[optind][1]) if (optind >= argc || !argv[optind] || argv[optind][0] != '-' || !argv[optind][1])
return -1; return -1;
if (argv[optind][1] == '-' && !argv[optind][2]) if (argv[optind][1] == '-' && !argv[optind][2])
......
...@@ -3,8 +3,15 @@ ...@@ -3,8 +3,15 @@
#include <getopt.h> #include <getopt.h>
#include <stdio.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) 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 (optind >= argc || !argv[optind] || argv[optind][0] != '-') return -1;
if ((longonly && argv[optind][1]) || if ((longonly && argv[optind][1]) ||
(argv[optind][1] == '-' && argv[optind][2])) (argv[optind][1] == '-' && argv[optind][2]))
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册