简体   繁体   English

C getopt不会读取所有参数

[英]C getopt does not read all the parameters

I have an assignment in C that requires options to be read in for different forms of a program. 我在C中有一个作业,需要为不同形式的程序读取选项。 Before I start on that, though, I want to make sure that the getopt portion is working fine. 不过,在开始之前,我想确保getopt部分工作正常。 However, the program keeps dropping the last parameter and I don't know why. 但是,程序不断删除最后一个参数,我不知道为什么。 Whenever I enter the last char, the program goes to the default value that kills the program. 每当我输入最后一个字符时,程序将使用默认值终止程序。 Any help is appreciated! 任何帮助表示赞赏!

#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>

int main(int argc, char **argv)
{
    int sFlag = 0;
    int lFlag = 0;
    int dFlag = 0;
    int rFlag = 0;
    int c;
    opterr = 0;

    while ((c = getopt (argc, argv, "slr:")) != -1)
    {
        switch(c)
        {
            case 's':
                sFlag = 1;
                break;
            case 'l':
                lFlag = 1;
                break;
            case 'r':
                rFlag = 1;
                break;
            default:
                printf("unknown parameter introduced");
                exit(-1);
                break;
        }
    }

    printf("s = %i, l = %i, d = %i, r = %i", sFlag, lFlag, dFlag, rFlag);

    return 1;
}

The colon symbol after r in "slr:" tells getopt() to wait for a mandatory argument which follows -r . "slr:" r后面的冒号表示告诉getopt()等待-r的强制性参数。

Examples: 例子:

  1. getopt(argc, argv, "slr:") can parse ./project -s -l -r r_arg (or ./project -r r_arg -s etc.) getopt(argc, argv, "slr:")可以解析./project -s -l -r r_arg (或./project -r r_arg -s等)
  2. getopt(argc, argv, "s:lr:") can parse ./project -s s_arg -l -r r_arg getopt(argc, argv, "s:lr:")可以解析./project -s s_arg -l -r r_arg
  3. getopt(argc, argv, "s:lr:") can also parse ./project -s -l -r r_arg with no error , but the program works differently from user's expectation. getopt(argc, argv, "s:lr:")也可以解析./project -s -l -r r_arg ,没有错误 ,但是程序的工作方式与用户的预期不同。 This is because getopt() expects -s to be followed by its argument, however it looks like, so the next argument -l is consumed and will not hit your switch(c) . 这是因为getopt()期望-s getopt()的参数,但是看起来像这样,因此下一个参数-l被消耗了,不会碰到switch(c)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM