В программе на C мне нужно разобрать опцию командной строки, для которой я использую функцию C getopt_long () с синтаксисом:
int getopt_long(int argc, char * const *argv, const char *optstring, const struct option *longopts, int *longindex);
Проблема в том, что я всегда получаю значение последнего параметра longindex как 0.
Ниже приведен пример кода:
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
static int verbose_flag;
int
main (int argc, char **argv)
{
int c;
printf("MAIN\n");
int i;
printf("argc = %d\n",argc);
for(i=0;i<argc;i++)
{
printf("argv[%d] = %s\n",i, argv[i]);
}
while (1)
{
static struct option long_options[] =
{
{"delete", required_argument, 0, 'd'},
{"create", required_argument, 0, 'c'},
{"file", required_argument, 0, 'f'},
{0, 0, 0, 0}
};
int option_index = 0;
c = getopt_long (argc, argv, "c:d:f:",
long_options, &option_index);
printf("\nOPT c = %d, option_index = %d START\n", c, option_index);
if (c == -1)
{
printf("BREAKKKKKKKKKKK\n");
break;
}
printf("OPTION FOUND c = %d, option_index = %d, long_options[option_index].name = %s\n", c, option_index, long_options[option_index].name);
switch (c)
{
case 0:
if (long_options[option_index].flag != 0)
break;
printf ("option %s", long_options[option_index].name);
if (optarg)
printf (" with arg %s", optarg);
printf ("\n");
break;
case 'c':
printf ("option -c with value `%s'\n", optarg);
break;
case 'd':
printf ("option -d with value `%s'\n", optarg);
break;
case 'f':
printf ("option -f with value `%s'\n", optarg);
break;
case '?':
break;
default:
abort ();
}
}
if (verbose_flag)
puts ("verbose flag is set");
if (optind < argc)
{
printf ("non-option ARGV-elements: ");
while (optind < argc)
printf ("%s ", argv[optind++]);
putchar ('\n');
}
return (0);
}
Выход:
MAIN
argc = 5
argv[0] = /home/a.out
argv[1] = -delete
argv[2] = dell
argv[3] = -create
argv[4] = ceat
OPT c = 100, option_index = 0 START
OPTION FOUND c = 100, option_index = 0, long_options[option_index].name = delete
option -d with value `elete'
OPT c = 99, option_index = 0 START
OPTION FOUND c = 99, option_index = 0, long_options[option_index].name = delete
option -c with value `reate'
OPT c = -1, option_index = 0 START
BREAKKKKKKKKKKK
non-option ARGV-elements: dell ceat
Я что-то упустил?
Почему мне всегда значение последнего параметра longindex равно 0?
Как исправить проблему?