getopt 不将可选参数解析为参数 [英] getopt does not parse optional arguments to parameters
本文介绍了getopt 不将可选参数解析为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 C 中,getopt_long 不会将可选参数解析为命令行参数参数.
当我运行程序时,无法识别可选参数,就像下面运行的示例一样.
$ ./respond --praise John向约翰致敬$ ./respond --责备约翰你好烂 !$ ./respond --责备你好烂 !
这是测试代码.
#include <stdio.h>#include <getopt.h>int main(int argc, char ** argv){int getopt_ret, option_index;静态结构选项 long_options[] = {{"赞美", required_argument, 0, 'p'},{"责备", optional_argument, 0, 'b'},{0, 0, 0, 0} };而(1){getopt_ret = getopt_long(argc, argv, "p:b::",long_options, &option_index);if (getopt_ret == -1) 中断;开关(getopt_ret){案例0:中断;案例p":printf("感谢 %s
", optarg);休息;案例b":printf("你糟透了");如果(可选参数)printf (", %s!
", optarg);别的printf ("!
", optarg);休息;案件 '?':printf("未知选项
");休息;}}返回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
", optarg); break;
case 'b':
printf("You suck ");
if (optarg)
printf (", %s!
", optarg);
else
printf ("!
", optarg);
break;
case '?':
printf("Unknown option
"); 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屋!
查看全文