我想用来getopt_long()
解析命令行参数。阅读getopt_long()
手册页后,我了解到getopt_long()
只能在选项之后解析一个参数。有没有办法getopt_long()
像这样解析这个命令行:
./a.out -s 127.0.0.1 2012 -u stackoverflow
给出结果:
ip = 127.0.0.1
port = 2012
username = stackoverflow
这是我尝试过的:
while (1) {
int this_option_optind = optind ? optind : 1;
int option_index = 0;
static struct option long_options[] = {
{"server", required_argument, NULL, 's'},
{"user", required_argument, NULL, 'u'},
{0, 0, 0, 0},
};
c = getopt_long(argc, argv, "s:u:", long_options, &option_index);
if (c == -1)
break;
switch (c) {
case 's':
printf("option %s", long_options[option_index].name);
if (optarg) {
printf(" with arg %s", optarg);
}
printf("\n");
case 'u':
printf("option %s", long_options[option_index].name);
if (optarg) {
printf(" with arg %s", optarg);
}
printf("\n");
case '?':
break;
default:
printf("?? getopt returned character code 0%o ??\n", c);
}
}