LINUX C 使用getopt函数以及其相关变量opterr optopt optind optarg

头文件

unistd.h.

函数及功能

int getopt (int argc , char *const * argv , const char * options )

该函数从argv和argcgetopt参数指定的参数列表中获取下一个选项参数。通常这些值直接来自接收到的参数 。options参数是一个字符串,它指定对该程序有效的选项字符。此字符串中的选项字符可以后跟冒号 (’:’) 表示它需要一个必需的参数。如果选项字符后跟两个冒号 (’::’),它的参数是可选的;这是一个 GNU 扩展。getopt有三种方法来处理非选项argv元素之后的选项, ‘–’ 强制在所有情况下结束选项扫描。

相关变量

int opterr
如果此变量的值不为零,则getopt在遇到未知选项字符或缺少必需参数的选项时将错误消息打印到标准错误流。这是默认行为。如果将此变量设置为零,getopt 则不会打印任何消息,但仍会返回? 指示错误的字符。

int optopt
当getopt遇到未知选项字符或缺少必需参数的选项时,它将该选项字符存储在此变量中。您可以使用它来提供您自己的诊断消息。

int optind
此变量设置为要处理的argv数组getopt的下一个元素的索引。找到所有选项参数后,您可以使用此变量来确定其余非选项参数的开始位置。该变量的初始值为。 getopt1

char * optarg
对于那些接受参数的选项,此变量设置getopt为指向选项参数的值。

代码示例:

通常,getopt在循环中调用。当getopt返回 -1,表示没有更多选项存在时,循环终止。

#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;
}

以下是一些示例,展示了该程序使用不同的参数组合打印的内容:
% testopt
aflag = 0, bflag = 0, cvalue = (null)

% testopt -a -b
aflag = 1, bflag = 1, cvalue = (null)

% testopt -ab
aflag = 1, bflag = 1, cvalue = (null)

% testopt -c foo
aflag = 0, bflag = 0, cvalue = foo

% testopt -cfoo
aflag = 0, bflag = 0, cvalue = foo

% testopt arg1
aflag = 0, bflag = 0, cvalue = (null)
Non-option argument arg1

% testopt -a arg1
aflag = 1, bflag = 0, cvalue = (null)
Non-option argument arg1

% testopt -c foo arg1
aflag = 0, bflag = 0, cvalue = foo
Non-option argument arg1

% testopt -a -- -b
aflag = 1, bflag = 0, cvalue = (null)
Non-option argument -b

% testopt -a -
aflag = 1, bflag = 0, cvalue = (null)
Non-option argument -
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

举世无双勇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值