在C中,getopt_long不解析命令行參數參數的可選參數。getopt不解析參數的可選參數
當我運行該程序時,可選參數不被識別,如下面的示例運行。
$ ./respond --praise John
Kudos to John
$ ./respond --blame John
You suck !
$ ./respond --blame
You suck !
這裏是測試代碼。
#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;
}
我在這裏回答了這個問題,所以其他人不需要把頭靠在牆上。 – hayalci 2009-06-27 12:38:01