我将getopt()机制用于我自己的类似argv的数组,在真正的argv上使用了它之后。接口是不可重入的(保持状态),并且各种实现以不同的方式重置。
我不想为此自动配置。
可靠的#ifdef集合是什么?
“重新启动” getopt()
的唯一标准方法是设置optind = 1
。
SUSv4 standard没有提及optreset
,并且将optind = 0
声明为“未指定”:
如果应用程序在调用前将
optind
设置为零getopt()
,行为未指定。
只要设置optind = 1
就可以使用
[a)您不使用任何GNU扩展名:
扫描多个参数向量或重新扫描相同参数的程序向量不止一次,并且想利用GNU扩展,例如optstring开头的
+
和-
,或更改[两次扫描之间的POSIXLY_CORRECT
,必须通过重置来重新初始化getopt()
optind
到0,
b)在返回[-1]之前,不要在中间重新启动getopt()
。例如。从FreeBSD的getopts
:
int
getopt(int nargc, char * const nargv[], const char *ostr)
{
static char *place = EMSG; /* option letter processing */
char *oli; /* option letter list index */
if (optreset || *place == 0) { /* update scanning pointer */
optreset = 0;
...
place = EMSG;
return (-1);
...
place = EMSG;
return (-1);
...
place = EMSG;
if (strchr(ostr, '-') == NULL)
return (-1);
...
} else
optopt = *place++;
...
return (BADCH);
...
return (BADARG);
...
return (BADCH);
...
return (optopt); /* return option letter */
}