1

我需要在 C 中解析命令行参数。我的参数基本上是 int 或 float,具有默认值和范围约束。

我已经开始实现如下所示的东西:

option_float(float* out, int argc, char* argv, char* name, description,
    float default_val, int is_optional, float min_value, float max_value)

例如,我称之为:

float* pct;
option_float(pct, argc, argv, "pct", "My super percentage option", 50, 1,
    FALSE, 0, 100)

但是我不想重新发明轮子!

My objective is to have error checking of range constraints, throw an error when the option is not optional and is not set. 并生成通常由 usage() 函数给出的帮助信息。

使用文本如下所示:

--pct     My super percentage option (default : 50). Should be in [0, 100]

我从 getopt 开始,但它对于我想做的事情太有限了,我觉得它仍然需要我为这样的简单用例编写太多代码。

你会推荐什么替代品?

4

1 回答 1

0

假设你正在为 Linux 编码......

尝试 getopt_long (man 3 getopt_long) 作为双破折号选项。

此外,尝试使验证器成为通用函数,并让 getopt/getopt_long 进入解析的困难部分并检查选项所需的参数。

在任何情况下,如果您想按定义使用函数,您的示例调用将无法按定义工作。

一个简化的例子:

int main( int argc, char **argv )
{
  float pct = 0.0
  if( !GetArgs(argc, argv, &pct) )
    DoStuff(pct)
}

int GetArgs( int argc, char **argv, float *thePct )
{
  extern char *optarg;
  int  rc = 0;

  (*thePct) = 50.0  /* default val */

  while( (opt = getopt(argc, argv, "hp:")) != -1 )
  {
    switch( opt )
    {
      case  'p':
            (*thePct) = atof( optarg );
            break;

      case  'h':
            MyUsage();  /* Explain everything */
            rc = -1;
            break;
    }
  }

  if( !rc )
  {
    rc = ValidatePct( (*thePct),   /* value to check */
                      0.0,         /* low pct val */
                      100.0 );     /* hi pct val */

    /* Other validations here */

    if( !rc )
      MyUsage();
  }
}

这将允许调用如下:

$ myprogram -p 45.0

如果您坚持使用解析器 getopt 和 getopt_long,您还可以制作带有选项的命令行,后跟 N 个其他参数,如 grep 所做的,例如:

grep -in -e "SomeRegex" file1, file2, ..., fileN

纯粹出于好奇,您不是 PERL 程序员,是吗?

于 2010-12-27T15:23:26.837 回答