Unix 如何防止getopt与缺少参数的选项混淆?

Unix 如何防止getopt与缺少参数的选项混淆?,unix,gcc,posix,libc,getopt,Unix,Gcc,Posix,Libc,Getopt,比如,我有代码: 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

比如,我有代码:

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();
    }
}
当我把我的程序称为

./main -n -p
它打印:

n: -p

为什么getopt不返回:表示缺少-n的参数,而是使用-p作为参数参数?

使用以破折号开头的选项参数,通常类似于另一个选项,这是完全可以的。getopt没有理由报告错误

如果一个程序不想接受这样的选项参数,它应该特别检查它们,例如

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

我有一个类似的问题,我让它落在默认情况下。不确定是否存在操作optopt变量的问题,但它似乎有效:

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

因为它不能读心。对于getopt,-p是一个合法的参数。如果它在您的程序中无效,您需要检查它的有效性。您的意思是:If(has_option(optarg)){err(“missing argument”);}?作为答案写入。