How to prevent getopt from being confused with option with missing argument?

蓝咒 提交于 2019-12-11 05:27:19

问题


Say, I have code:

while ((c = getopt(argc, argv, ":n:p")) != -1) {
    switch (c) {
    case 'n':
        syslog(LOG_NOTICE, "n: %s", optarg);
        break;
    case 'p':
        /* ... some code ... */
        break;
    case ':':
        /* handle missing arguments to options requiring arguments */
        break;
    /* some cases like '?', ... */
    default:
        abort();
    }
}

When I call my program as

./main -n -p

it prints:

n: -p

Why does not getopt return : to indicate that argument to -n is missing but instead uses -p as parameter argument?


回答1:


It is perfectly OK to have an option argument that starts with a dash and generally resembles another option. There is no reason for getopt to report an error.

If a program doesn't want to accept such option arguments, it should specifically check for them, e.g.

   if (optarg[0] == '-') {
      // oops, looks like user forgot an argument
      err("Option requires an argument");
   }



回答2:


I had a similar issue, I let it fall through to the default case. not sure if manipulating the optopt variable is an issue, but it seems to work:

while ((c = getopt(argc, argv, "a:d:x")) != -1)
{
    switch (c) 
    {
        case 'a':
            if (optarg[0] == '-' && err == 0)
            {
                err = 1;
                optopt = 'a';
            }
            else if (err == 0)
            {
                aflag = 1;
                aArg = optarg;
                break;
            }
        case 'd':
            if (optarg[0] == '-' && err == 0)
            {
                err = 1;
                optopt = 'd';
            }
            else if (err == 0)
            {
                dflag = 1;
                dArg = optarg;
                break;
            }
        case 'x':
            if (err == 0)
            {
                xflag = 1;
                break;
            }
        default:
            if (optopt == 'a' || optopt == 'd')
            {
                fprintf(stderr, "Option -%c requires an argument.\n", optopt);
                return 1;
            }
            else
            {
                fprintf(stderr, "Unknown option '-%c'\n", optopt);
                return 2;
            }
    }//end of switch
}//end of while


来源:https://stackoverflow.com/questions/40360368/how-to-prevent-getopt-from-being-confused-with-option-with-missing-argument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!