Parsing command line options with multiple arguments [getopt?]

前端 未结 3 2032
轮回少年
轮回少年 2021-01-31 11:36

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

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

So, I need to get

相关标签:
3条回答
  • 2021-01-31 11:41

    I wrote a C library(GPL license) for parsing command line arguments:

    https://github.com/Vincenzo1968/myoptParser

    https://github.com/Vincenzo1968/myoptParser/blob/master/how_to_use.md

    You can specify the minimum and the maximum number of arguments that option accepts. You can also specify that an option takes zero or more arguments (or one or more, two or more, and so on). And, of course, you can specify a fixed number of arguments: zero, one, two, and so on.

    You can also specify the type of the arguments: string, integer or float. The parser checks that the number and type specified matches and, otherwise, it returns an error.

    The parser also allows you to specify whether an option is required or not. You can finally specify the mutually exclusive options.

    0 讨论(0)
  • 2021-01-31 11:46

    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 stores that information in the global variable optind. When I added the line:

    optind = index - 1;
    

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

    0 讨论(0)
  • 2021-01-31 11:51

    The following function will generate an argc, argv pair for a single option within an argument list:

    void GetArgsList (int argc, char *argv[], int* o_argc, char*** o_argv)
    {
        char** ret = NULL;
        int i;
        int count = 0;
    
        for (i = optind - 1; i < argc ; ++i)
        {
            if (argv[i][0]=='-')
            {
                break;
            }
            else
            {
                if (NULL == ret)
                {
                    ret = &argv[i];
                }
                count++;
            }
        }
    
        optind = i - 1;
    
        if (o_argc)
        {
            *o_argc = count;
        }
    
        *o_argv = ret;
    }
    
    0 讨论(0)
提交回复
热议问题