c语言可选参数解析命令,c-getopt不会将可选参数解析为参数

本文深入解析getopt_long函数的使用方法及注意事项,包括如何处理选项参数、非选项参数及长选项等复杂情况。

手册页当然没有很好地说明它,但是源代码有一点帮助。

简而言之:您应该做类似以下的事情(尽管这可能有点过度学究):

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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值