#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <string.h>
int main(int argc, char **argv) {
int o;
int w = 10;
while ((o = getopt(argc, argv, "w::")) != -1) {
switch (o) {
case 'w' :
if (optarg) {
w = atoi(optarg);
}
break;
}
}
printf("%d\n", w);
}
I want this to work
$ gcc -Wall theup.c
$ ./a.out -w 17
17
Currently does this
$ gcc -Wall theup.c
$ ./a.out -w 17
10
Is there any way to do this with getopt? It works for most of them like -w17 -w , but the space one doesn't work
with :: (allows not to pass a value after the option), and a space, there would be an ambiguity between -w 17 where 17 would be the value of the option and -w 17 where 17 is another argument, which explains that getopt requires that the value is collated when using ::
Even worse, think of the general case where there are other options. What would -w -x do ? getopt cannot predict that you're requiring a number after your option.
I would just change the getopt line to:
while ((o = getopt(argc, argv, "w:")) != -1) {
now omitting -w still gives 10 as the value is defaulted beforehand.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With