getopt how to set a default value

2019-07-14 07:10发布

问题:

#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' :
                w = atoi(optarg);
                break;



        }

    }
    printf("%d\n", w);
}

Basically, I want -w to have if nothing is inputted.

Consider these use cases

$ gcc -Wall fileabove.c
$ ./a.out 
10
$ ./a.out -w
10
$ ./a.out -w14
14

I can't get the second one to work. Is there any way I can play around with getopt to get the expected result?

回答1:

Assuming you're using GNU getopt, the following should work:

    while ((o = getopt(argc, argv, "w::")) != -1) {
        switch (o) {
            case 'w' :
                if (optarg) {
                    w = atoi(optarg);
                }
                break;

A following : marks the option as requiring an argument. A double : makes the argument optional (this is a GNU extension). If there is no argument, optarg is NULL.



标签: c getopt