Parsing command line options with multiple arguments [getopt?]

前端 未结 3 2118
轮回少年
轮回少年 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: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.

提交回复
热议问题