Frage

I met a problem when using getopt_long in C. As is descripted, in the structure as follows:

struct option{ 
         const char *name; 
         int has_arg; 
         int *flag; 
         int val; 
};

If flag is set, getopt_long should return 0 and set *flag as val. But in my code, getopt_long return val and *flag stay unchanged. The code is as follows:

#include<stdio.h>
#include<getopt.h>

int help;
int output;
int verbose;

const char *short_option = "ho:v";
const struct option long_options[] = {
    {"help", 0, &help, 'h'},
    {"output", 1, &output, 'o'},
    {"verbose", 0, &verbose, 'v'},
    {NULL, 0, NULL, 0}
};

void print_help()
{
    printf("in option help: \n");
}

void print_output(char *content)
{
    printf("in option output: argument is %s\n",content);
}

void print_verbose()
{
    printf("in option verbose\n");

}

void print_args()
{
    printf("help is %d\n",help);
    printf("output is %d\n",output);
    printf("verbose is %c\n",verbose);
}

int main(int argc, char **argv)
{
    int next_option;
    while( (next_option = getopt_long(argc, argv, short_option, long_options, NULL )) == 0)
    {
        printf("next_option is %c\n",next_option);
        print_args();
    }

    return 0;
}

Anyone can help?

War es hilfreich?

Lösung

If you check the manual page, you will see that:

getopt_long() and getopt_long_only() also return the option character when a short option is recognized. For a long option, they return val if flag is NULL, and 0 otherwise.

So if you use the short option when invoking your program, it will return that option character. For the function to behave as you want, you must use the long argument when invoking your program.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top