getopt的不解析可选参数的参数 [英] getopt does not parse optional arguments to parameters
本文介绍了getopt的不解析可选参数的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在C,getopt_long不解析可选参数的命令行参数的参数。
当我运行该程序,可选参数无法识别像下面运行的例子。
$ ./respond --praise约翰
荣誉约翰
$ ./respond --blame约翰
你好烂 !
$ ./respond --blame
你好烂 !
下面是测试code。
的#include<&stdio.h中GT;
#包括LT&;&getopt.h GT;INT主(INT ARGC,字符** 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);
如果(getopt_ret == -1)破; 开关(getopt_ret)
{
情况下0:打破;
案例'P':
的printf(荣誉到%s \\ n,OPTARG);打破;
案例'B':
的printf(你吸);
如果(OPTARG)
的printf(%S \\ n!,OPTARG);
其他
的printf(,OPTARG\\ n!);
打破;
案件 '?':
的printf(未知的选项\\ n);打破;
}
}
返回0;
}
解决方案
尽管glibc的文档或getopt的手册页中未提到,可选参数长风格的命令行参数要求等号(=)。从空间参数分离的可选参数不工作。
一个例子与测试code运行:
$ ./respond --praise约翰
荣誉约翰
$ ./respond --praise =约翰
荣誉约翰
$ ./respond --blame约翰
你好烂 !
$ ./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屋!
查看全文