如何防止getopt与缺少参数的选项混淆? [英] How to prevent getopt from being confused with option with missing argument?
本文介绍了如何防止getopt与缺少参数的选项混淆?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
while((c = getopt(argc,argv,:n:p ))!= -1){
switch(c){
case'n':
syslog(LOG_NOTICE,n:%s,optarg);
休息;
案例'p':
/ * ...一些代码... * /
break;
case':':
/ *处理需要参数的选项缺少的参数* /
break;
/ *一些例如'?',... * /
默认值:
abort();
当我将我的程序称为
./ main -n -p
打印:
n:-p
为什么不使用getopt返回:指示缺少-n参数,而是使用-p作为参数参数?
解决方案
具有以破折号开头的选项参数并且通常类似于其他选项是完全可以的。 getopt没有理由报告错误。
如果程序不想接受这样的选项参数,它应该专门检查它们,例如
if(optarg [0] ==' - '){
// oops,看起来像用户忘记了一个参数
err(Option需要参数);
}
Say, I have code:
while ((c = getopt(argc, argv, ":n:p")) != -1) {
switch (c) {
case 'n':
syslog(LOG_NOTICE, "n: %s", optarg);
break;
case 'p':
/* ... some code ... */
break;
case ':':
/* handle missing arguments to options requiring arguments */
break;
/* some cases like '?', ... */
default:
abort();
}
}
When I call my program as
./main -n -p
it prints:
n: -p
Why does not getopt return : to indicate that argument to -n is missing but instead uses -p as parameter argument?
解决方案
It is perfectly OK to have an option argument that starts with a dash and generally resembles another option. There is no reason for getopt to report an error.
If a program doesn't want to accept such option arguments, it should specifically check for them, e.g.
if (optarg[0] == '-') {
// oops, looks like user forgot an argument
err("Option requires an argument");
}
这篇关于如何防止getopt与缺少参数的选项混淆?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文