Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getopt flexibility to make spaces work as well

Tags:

c

#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

like image 280
e t Avatar asked Jan 18 '26 17:01

e t


1 Answers

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.

like image 175
Jean-François Fabre Avatar answered Jan 21 '26 09:01

Jean-François Fabre