【问题标题】:How to efficiently parse command-line arguments in C如何有效地解析 C 中的命令行参数
【发布时间】:2022-09-28 23:17:20
【问题描述】:

我有一个程序需要解析命令行参数并将它们传递给各种函数以执行不同的任务。

一些可能的选项和可能的论点是:

  • -a <source> <destination>
  • -b <filename>
  • -p --num <number>
  • -r --identical <source> <destination>
  • -g --alphabetical <destination>

如您所见,各种选项非常多样化,不仅限于-f <x> 之类的简单选项,而是还具有各种参数和参数(例如-r)。

我研究了getopt_long/getopt,但这些并不能完全满足我的所有程序选项。例如我不能做-r --identical <source> <destination>

所以我求助于解析自己:


#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[])
{

     if (argc == 1)
     {
         fprintf(stderr,\"no args\");
         return -1;
     }

     if (argc == 4)
     {
        if (strncmp(\"-a\", argv[1], 3) == 0)
        {
            a_function(argv[2], argv[3]);
        }
     }
     else if (argc == 3)
     {
          if (strncmp(\"-b\", argv[1], 3) == 0)
          {
              another_func(argv[2]);
          }
     }


    return 0;
}

上面的程序依赖于提供的参数的数量,我的问题是:有没有更有效/更干净的方法来解析参数(特别是我上面定义的那些),因为如果我继续,那么我的程序将有一个巨大的 @ 列表987654333@ 语句,看起来一点也不干净。如果有更好和更有效的方法,我将不胜感激在实施它方面的一些帮助。

标签: c arguments command-line-arguments argv argc


【解决方案1】:

这是一项相当复杂的任务,我建议使用现成的库。

  1. POSIXgetopt https://www.gnu.org/software/libc/manual/html_node/Getopt.html 或者

  2. GNU argp https://www.gnu.org/software/libc/manual/html_node/Argp.html

【讨论】:

    【解决方案2】:

    这个库会干净利落地完成任务:https://github.com/XUJINKAI/cmdparser/

    下面的基本示例,它还支持嵌套的子命令(如 git)等。

    static cmdp_command_st cmdp = {
        .options = {
            {'i', "Int", "Input Int Option", CMDP_TYPE_INT4, &arg.i},
            {0},
        },
        .fn_process = callback,
    };
    
    int main(int argc, char **argv)
    {
        return cmdp_run(argc - 1, argv + 1, &cmdp);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-07
      • 1970-01-01
      • 2011-04-27
      • 2013-02-15
      相关资源
      最近更新 更多