在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?
如何解决这个问题?

最佳答案

argv[…] = …输出中,您似乎错误地使用了长选项。而不是像这样调用程序

/home/a.out -delete dell -create creat


像这样调用它:

/home/a.out --delete dell --create creat


这将导致索引设置正确。

查看getopt_long(3) manpage的“说明”部分,以获取有关如何使用长选项的详细信息。

关于c - getopt_long()的longindex始终为0,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55610476/

10-11 19:07