getopt_long() 的 longindex 总是 0

getopt_long()'s longindex always 0

在 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“描述”部分,了解有关如何使用长选项的详细信息。