重置getopt()的可移植方式是什么?

问题描述 投票:0回答:1

我将getopt()机制用于我自己的类似argv的数组,在真正的argv上使用了它之后。接口是不可重入的(保持状态),并且各种实现以不同的方式重置。

  • 在XPG3 / SVID中,它是“ optreset = 1;” (freebsd,macosx)
  • 在XPG4 / POSIX / SUS中,它是“ optind = 1;” (使用风滚草)
  • 在Linux / GLIBC中,它也是“ optind = 0;” (debian)

我不想为此自动配置。

可靠的#ifdef集合是什么?

posix libc getopt sus
1个回答
0
投票

“重新启动” 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 */
}
© www.soinside.com 2019 - 2024. All rights reserved.