0

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

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");
        }
    }
}

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

./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!!!
4

1 回答 1

8

我认为混乱源于对 long get opt 的误解。本质上,它只会在您使用--表单时进行部分字符串匹配。当您仅使用-它时,它将回退到标准解析,因此-por 80匹配为-p or 80(如,选项是-p,参数是or)。--po用and尝试同样的事情--por。至于帮助,请尝试--he--hel

于 2011-09-20T20:26:28.800 回答