解析具有多个参数的命令行选项[getopt?]

Sal*_*der 16 c parsing command-line-arguments

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

getpwd -l user1 user2 ... -L -X -S...
Run Code Online (Sandbox Code Playgroud)

所以,我需要让用户背后的-l选项.我尝试过使用getopt,但没有太多运气,只有当我将其他选项放在-l:

getpwd -L -X -S ... -l user1 user2 ...
Run Code Online (Sandbox Code Playgroud)

我的代码(for -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;
      }
   }
Run Code Online (Sandbox Code Playgroud)

optopt并且optindextern int.

所以,问题是:我可以使用getopt()函数(或getopt_long())吗?或者我是否必须编写自己的解析器来获得我需要的东西?

rra*_*rra 13

你的代码实际上非常非常接近于工作.你唯一缺少的是getopt只希望你在之后使用一个参数-l,因此在第一个参数之后继续命令行解析-l.因为你要支持更多的参数,你必须告诉从getopt哪里开始再次解析命令行.

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

optind = index - 1;
Run Code Online (Sandbox Code Playgroud)

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

  • 由于某种原因,`optind = index-1`对我有用...明天我会更仔细地研究它。但是,非常感谢。我对此功能感到惊讶...我发现到处都无法使用getopts():D (2认同)