问题
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