Оптарг всегда ноль
Оптарг всегда нулевой. Приложение вылетает.
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 != '\0')
{
printf(usage_template);
}
port = (uint16_t)htons(value);
}
break;
case '?':
printf(usage_template);
exit(0);
case -1:
break;
default:
exit(0);
}
} while (nextOption != -1);
Кто-нибудь может мне помочь с этим вопросом?
1 ответ
Решение
Похоже, что за вашей опцией "p" не стоит двоеточие, поэтому getopt не ожидает, что у нее будет аргумент.