【问题标题】:CLI arguments in CC 中的 CLI 参数
【发布时间】:2011-08-09 03:16:26
【问题描述】:

我们正在开发一个程序,该程序应该接受同一参数的多个输入。例如。

program1 -A arg1 -A arg2 -A arg3 -B arg4 -B arg5 -B arg6

更复杂的是,-A 和 -B 参数具有 1:1 的关系。所以 arg1 映射到 arg4 等等。

那么上面的例子是提供多个相同参数列表的最佳方式吗?或者这是公认的方式?

【问题讨论】:

    标签: c command-line-interface command-line-arguments


    【解决方案1】:

    C 语言提供函数getopt 来解析命令行选项。 getopt_long 函数是一个 GNU 扩展,它解析提供比 getopt 更多功能的命令行选项,例如多字符选项解析。你可以在这里找到文档:http://linux.die.net/man/3/getopt_long 或者只是一个男人 getopt_long。 让我举个例子。假设您有一个具有 3 个选项的程序(-h 用于帮助消息,-i 用于显示整数,-s 用于显示字符串)。首先,你必须声明一个struct options。此结构将包含您的程序需要的所有选项,并且定义如下:

        struct option {
        const char *name; // the option name
        int has_arg; // if your option has an argument - no_argument (equivalent to 0) if no option and required_argument otherwise (1)
        int *flag; // specifies how results are returned for a long option. If flag is NULL, then getopt_long() returns val
        int val; // is the value to return, or to load into the variable pointed to by flag.
    };
    

    由于你的程序有很多选项,你必须声明一个结构体选项数组:

    struct option options[] = {
    {"help", no_argument, NULL, 'h'}, // for the help msg
    {"int", 1, required_argument, 'i'}, // display an int
    {"string", required_argument, NULL, 's'}, // displays a string
    {NULL, 0, NULL, 0}};
    

    你的选择如下:

     int main(int argc, char* argv[]){
    
          char opt;
         while ((opt = getopt_long (argc, argv, "his:", options, NULL)) != -1) {
      switch(opt){
            case 'h': printf("Help message \n"); exit(0);
            case 'i': printf("Int options = %d\n", optarg);break;
            case 's': printf("String option = %s\n", optarg); break;
            default:  printf("Help message\n");
       }
    
        }
    

    不要忘记包含 "getopt.h"

    祝你好运

    【讨论】:

    • getopt_long 是一个 GNU 扩展。它不是C语言提供的!它甚至不是由 POSIX 扩展提供的; POSIX 扩展提供了功能较弱的getopt。
    【解决方案2】:

    没有更多信息,有点模糊。不过,我的意见是像这样匹配它们

    cmd -pair1 argA1 argB1 -pair2 argA2 argB2 ...
    

    或者可能类似于以下内容。经过一番思考,我更喜欢这个,因为它是匹配参数的最简单方法,无需输入大量参数“类型”,这不是必需的。

    cmd argA1 argB1 argA2 argB2 ...
    

    【讨论】:

    • 我喜欢你提供的第一种方法。谢谢。
    【解决方案3】:

    如果您是从头开始,您可能会考虑这样的事情:

    program1 arg1,arg4 arg2,arg4 arg3,arg6
    

    这将按照您描述的方式对参数进行配对,并用某个字符(在此示例中为逗号)分隔每一对。您可以选择适合您的分隔符。

    如果您不需要,则无需使用-X 选项约定。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-25
      • 2011-01-25
      • 2015-04-21
      • 1970-01-01
      • 1970-01-01
      • 2017-04-04
      相关资源
      最近更新 更多