getopt_long问题

fun*_*der 0 c getopt-long command-line-arguments

从我正在编写的程序中解析参数时遇到问题,代码如下:

void parse_args(int argc, char** argv)
{
    char ch;
    int index = 0;

    struct option options[] = {       
        { "help", no_argument, NULL, 'h'   },      
        { "port", required_argument, NULL, 'p'  },      
        { "stop", no_argument, NULL, 's' },         
        { 0,    0,    0,    0   }       
    };

    while ((ch = getopt_long(argc, argv, "hp:s", options, &index)) != -1) {
        switch (ch) {
            case 'h':   
                printf("Option h, or --help.\n");
                break;
            case 's':
                printf("Option s, or --stop.\n");

                break;
            case 'p':
                printf("Option p, or --port.\n");
                if (optarg != NULL)
                    printf("the port is %s\n", optarg);
                break;
            case '?':
                printf("I don't understand this option!!!\n");

            case -1:  
                break;
            default:
                printf("Help will be printed very soon -:)\n");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当我运行我的程序时,我得到一些奇怪的输出:

./Server -p 80
Option p, or --port.
the port is 80

./Server -po 80
Option p, or --port.
the port is o

./Server -por 80
Option p, or --port.
the port is or

./Server -hoho
Option h, or --help.
Server: invalid option -- o
I don't understand this option!!!
Run Code Online (Sandbox Code Playgroud)

Foo*_*Bah 7

我认为混淆源于对长期选择的误解.基本上,只有在使用--表单时才会进行部分字符串匹配.当你只使用-它时,它将回退到标准解析,因此-por 80匹配为-p or 80(如,选项是-p,参数是or).用--po和尝试相同的东西--por.至于帮助,尝试--he--hel