在C中使用getopt作为命令行参数 [英] Using getopt in C for command line arguments

查看:147
本文介绍了在C中使用getopt作为命令行参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试接受命令行参数.如果我想有多个可选的命令行参数,我该怎么做呢?例如,您可以通过以下方式运行程序: (每个实例都需要a,但是-b -c -d可以选择以任意顺序给出)

I am working on trying to take in command line arguments. If I want to have multiple optional command line arguments how would I go about doing that? For example you can run the program in the following ways: (a is required every instance but -b -c -d can be given optionally and in any order)

./myprogram -a
./myprogram -a -c -d
./myprogram -a -d -b

我知道getopt()的第三个参数是选项.我可以将这些选项设置为"abc",但是设置开关盒的方式会导致每个选项的循环中断.

I know that getopt()'s third argument is options. I can set these options to be "abc" but will the way I have my switch case set up causes the loop to break at each option.

推荐答案

getopt()而言,顺序无关紧要.重要的是您对getopt()的第三个参数(即,它是格​​式字符串)是正确的:

The order doesn't matter so far as getopt() is concerned. All that matters is your third argument to getopt() (ie: it's format string) is correct:

以下格式字符串都是等效的:

The follow format strings are all equivalent:

"c:ba"
"c:ab"
"ac:b"
"abc:"

在您的特定情况下,格式字符串只需要类似于"abcd"之类的内容,并且switch()语句已正确填充.

In your particular case, the format string just needs to be something like "abcd", and the switch() statement is properly populated.

下面的最小示例¹将有所帮助.

The following minimal example¹ will help.

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int
main (int argc, char **argv)
{
  int aflag = 0;
  int bflag = 0;
  char *cvalue = NULL;
  int index;
  int c;

  opterr = 0;

  while ((c = getopt (argc, argv, "abc:")) != -1)
  {
    switch (c)
      {
      case 'a':
        aflag = 1;
        break;
      case 'b':
        bflag = 1;
        break;
      case 'c':
        cvalue = optarg;
        break;
      case '?':
        if (optopt == 'c')
          fprintf (stderr, "Option -%c requires an argument.\n", optopt);
        else if (isprint (optopt))
          fprintf (stderr, "Unknown option `-%c'.\n", optopt);
        else
          fprintf (stderr,
                   "Unknown option character `\\x%x'.\n",
                   optopt);
        return 1;
      default:
        abort ();
      }
  }

  printf ("aflag = %d, bflag = %d, cvalue = %s\n",
          aflag, bflag, cvalue);

  for (index = optind; index < argc; index++)
    printf ("Non-option argument %s\n", argv[index]);
  return 0;
}

¹示例摘自GNU手册

这篇关于在C中使用getopt作为命令行参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆