解析带有多个参数的命令行选项[getopt?] [英] Parsing command line options with multiple arguments [getopt?]

查看:646
本文介绍了解析带有多个参数的命令行选项[getopt?]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要我的程序从命令行获取多个参数,语法如下:

I need my program to get several arguments from command line, the syntax is as follows:

getpwd -l user1 user2 ... -L -X -S...

因此,我需要将用户吸引到-l选项的后面.我尝试使用getopt,但运气不佳,仅当将其他选项放在-l之前时,它才起作用:

So, I need to get the users behind the -l option. I tried using getopt, but without much luck, it only works when I place the other options before the -l:

getpwd -L -X -S ... -l user1 user2 ...

我的代码(用于-l-S):

    while((c = getopt(argc, argv, "l:S")) != -1){
    switch(c){
        case 'l':
            index = optind-1;
            while(index < argc){
                next = strdup(argv[index]); /* get login */
                index++;
                if(next[0] != '-'){         /* check if optarg is next switch */
                    login[lcount++] = next;
                }
                else break;
            }
            break;
        case 'S':
            sflag++;                        /* other option */
            break;
        case ':':                           /* error - missing operand */
            fprintf(stderr, "Option -%c requires an operand\n", optopt);
            break;
        case '?':                           /* error - unknown option */
            fprintf(stderr,"Unrecognized option: -%c\n", optopt);
            break;
      }
   }

optoptoptindextern int.

因此,问题是:我可以使用getopt()函数(或getopt_long())吗?还是我必须编写自己的解析器才能获得所需的内容?

So, the question is: Can I use the getopt() function (or getopt_long()) ? Or do I have to write my own parser to get what I need ?

推荐答案

您的代码实际上非常非常接近工作.您唯一缺少的是getopt仅希望您在-l之后使用一个参数,因此会在-l的第一个参数之后继续命令行解析.由于要退后一步并提取更多参数,因此必须告诉getopt从哪里开始重新解析命令行.

Your code was actually very, very close to working. The only thing you were missing is that getopt only expects you to consume one argument after -l, and therefore continues command line parsing following the first argument to -l. Since you're going behind its back and pulling off more arguments, you have to tell getopt where to start parsing the command line again.

getopt将该信息存储在全局变量optind中.当我添加该行时:

getopt stores that information in the global variable optind. When I added the line:

optind = index - 1;

l情况下的break;之前,您的代码开始工作.

before the break; in your l case, your code started working.

这篇关于解析带有多个参数的命令行选项[getopt?]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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