手册页当然没有很好地说明它,但是源代码有一点帮助。
简而言之:您应该做类似以下的事情(尽管这可能有点过度学究):
if( !optarg
&& optind < argc // make sure optind is valid
&& NULL != argv[optind] // make sure it's not a null string
&& '\0' != argv[optind][0] // ... or an empty string
&& '-' != argv[optind][0] // ... or another option
) {
// update optind so the next getopt_long invocation skips argv[optind]
my_optarg = argv[optind++];
}
/* ... */
在_getopt_internal之前的注释中:
...
如果optarg找到另一个选项字符,则返回该字符, 更新optarg和optarg,以便下次致电
if the 3rd argument to getopt_long starts with a dash, argv will not
be permuted可以 使用以下选项字符或ARGV元素恢复扫描。
如果没有更多的选项字符,则optarg返回-1。 那么optarg是第一个ARGV元素在ARGV中的索引 那不是一个选择。 (ARGV元素已被置换 因此,那些不是选项的选项将排在最后。)
if the 3rd argument to getopt_long starts with a dash, argv will not
be permuted
...
如果OPTSTRING中的一个字符后跟一个冒号,则表示它需要一个arg, 因此以下文字在同一ARGV元素中,或以下文字 ARGV元素在optarg中返回。两个冒号表示一个选项, 需要一个可选的arg; 如果当前ARGV元素中有文字, 它在optarg中返回,否则optarg设置为零。
...
...尽管您必须在两行之间进行一些阅读。 以下是您想要的:
#include
#include
int main(int argc, char* argv[] ) {
int getopt_ret;
int 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) ) ) {
const char *tmp_optarg = optarg;
switch( getopt_ret ) {
case 0: break;
case 1:
// handle non-option arguments here if you put a `-`
// at the beginning of getopt_long's 3rd argument
break;
case 'p':
printf("Kudos to %s\n", optarg); break;
case 'b':
if( !optarg
&& NULL != argv[optindex]
&& '-' != argv[optindex][0] ) {
// This is what makes it work; if `optarg` isn't set
// and argv[optindex] doesn't look like another option,
// then assume it's our parameter and overtly modify optindex
// to compensate.
//
// I'm not terribly fond of how this is done in the getopt
// API, but if you look at the man page it documents the
// existence of `optarg`, `optindex`, etc, and they're
// not marked const -- implying they expect and intend you
// to modify them if needed.
tmp_optarg = argv[optindex++];
}
printf( "You suck" );
if (tmp_optarg) {
printf (", %s!\n", tmp_optarg);
} else {
printf ("!\n");
}
break;
case '?':
printf("Unknown option\n");
break;
default:
printf( "Unknown: getopt_ret == %d\n", getopt_ret );
break;
}
}
return 0;
}
本文深入解析getopt_long函数的使用方法及注意事项,包括如何处理选项参数、非选项参数及长选项等复杂情况。
2894

被折叠的 条评论
为什么被折叠?



