getopt 不解析参数的可选参数 [英] getopt does not parse optional arguments to parameters

查看:32
本文介绍了getopt 不解析参数的可选参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C 中,getopt_long 不会解析命令行参数的可选参数.

当我运行程序时,无法识别可选参数,就像下面运行的示例一样.

$ ./respond --praise John向约翰致敬$ ./respond -- 怪约翰你好烂 !$ ./response --blame你好烂 !

这是测试代码.

#include #include int main(int argc, char ** argv ){int getopt_ret, option_index;静态结构选项 long_options[] = {{赞美",required_argument,0,'p'},{"blame", optional_argument, 0, 'b'},{0, 0, 0, 0} };而 (1) {getopt_ret = getopt_long( argc, argv, "p:b::",long_options, &option_index);如果(getopt_ret == -1)中断;开关(getopt_ret){情况0:中断;案例'p':printf("感谢 %s\n", optarg);休息;案例'b':printf("你太烂了");如果(选择参数)printf (", %s!\n", optarg);别的printf ("!\n", optarg);休息;案件 '?':printf("未知选项\n");休息;}}返回0;}

解决方案

尽管在 glibc 文档或 getopt 手册页中没有提到,长样式命令行参数的可选参数需要等号"(=).将可选参数与参数分隔开的空格不起作用.

使用测试代码运行的示例:

<块引用>

$ ./respond --praise John向约翰致敬$ ./respond --praise=约翰向约翰致敬$ ./respond -- 怪约翰你好烂 !$ ./respond --blame=约翰你很烂,约翰!

In C, getopt_long does not parse the optional arguments to command line parameters parameters.

When I run the program, the optional argument is not recognized like the example run below.

$ ./respond --praise John
Kudos to John
$ ./respond --blame John
You suck !
$ ./respond --blame
You suck !

Here is the test code.

#include <stdio.h>
#include <getopt.h>

int main(int argc, char ** argv )
{
    int getopt_ret, option_index;
    static struct option long_options[] = {
               {"praise",  required_argument, 0, 'p'},
               {"blame",  optional_argument, 0, 'b'},
               {0, 0, 0, 0}       };
    while (1) {
        getopt_ret = getopt_long( argc, argv, "p:b::",
                                  long_options,  &option_index);
        if (getopt_ret == -1) break;

        switch(getopt_ret)
        {
            case 0: break;
            case 'p':
                printf("Kudos to %s\n", optarg); break;
            case 'b':
                printf("You suck ");
                if (optarg)
                    printf (", %s!\n", optarg);
                else
                    printf ("!\n", optarg);
                break;
            case '?':
                printf("Unknown option\n"); break;
        }
    } 
    return 0;
}

解决方案

Although not mentioned in glibc documentation or getopt man page, optional arguments to long style command line parameters require 'equals sign' (=). Space separating the optional argument from the parameter does not work.

An example run with the test code:

$ ./respond --praise John
Kudos to John
$ ./respond --praise=John
Kudos to John
$ ./respond --blame John
You suck !
$ ./respond --blame=John
You suck , John!

这篇关于getopt 不解析参数的可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆