Optarg 始终为空
Optarg is alway null
本文关键字:Optarg 更新时间:2023-10-16
Optarg 始终为 null。应用程序崩溃。
static const char* const short_options = "a:h:p";
static const struct option long_options[] =
{
{ "address", 1, NULL, 'a' },
{ "help", 0, NULL, 'h' },
{ "port", 1, NULL, 'p' }
};
我试图将空字符串添加到long_options,但没有帮助。
static const struct option long_options[] =
{
{ "address", 1, NULL, 'a' },
{ "help", 0, NULL, 'h' },
{ "port", 1, NULL, 'p' },
{0, 0, NULL, 0 }
};
但这并没有帮助。
有使用optarg的例子。我以同样的方式使用 optarg,但得到空。
do {
nextOption = getopt_long(argc, argv, short_options, long_options, NULL);
switch (nextOption)
{
case 'a':
{
//do something
}
break;
case 'h':
printf(usage_template);
exit(0);
case 'p':
{
long value;
char* end;
value = strtol(optarg, &end, 10);//OPTARG IS NULL
if (*end != ' ')
{
printf(usage_template);
}
port = (uint16_t)htons(value);
}
break;
case '?':
printf(usage_template);
exit(0);
case -1:
break;
default:
exit(0);
}
} while (nextOption != -1);
任何人都可以帮助我解决这个问题吗?
看起来你的"p"选项后面没有冒号,所以getopt不希望它有一个参数。