Home > Net >  how to use long options in c?
how to use long options in c?

Time:11-10

how to use long options via getopt_long:
for example like this:

--wide-option

I have --wide and -w.
And on --wide-option it gives the following error:

"unrecognized option"

int main(int argc, char **argv)
{
    struct option opts[] =
    {
        {"wide", 1, 0, 'w'},
        {
            0, 0, 0, 0
        }
    };
    int option_val = 0;
    int counter = 10;
    int opindex = 0;
    while ((option_val = getopt_long(argc, argv, "w:", opts, &opindex)) != -1)
    {
        switch (option_val)
        {
        case 'w':
            if (optarg != NULL)
                counter = atoi(optarg);
            for (int i = 0; i < counter; i  )
                printf("Hello world\n");
            break;
        default:
            return 0;
        }
    }
    return 0;
}

CodePudding user response:

If you look at the cat source code (here), you can see that --number and --number-nonblank are two different options (-b and -n). (near line 555).

If you want to do the same, you can that way:

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

int main(int argc, char **argv)
{
    struct option opts[] =
    {
        {"wide", 1, 0, 'w'},
        {"wide-option", 0, 0, 'o'}, /* declare long opt here */
        {
            0, 0, 0, 0
        }
    };
    int option_val = 0;
    int counter = 10;
    int opindex = 0;
    while ((option_val = getopt_long(argc, argv, "w:o", opts, &opindex)) != -1) /* the case here (I arbitrary choose 'o') */
    {
        switch (option_val)
        {
        case 'w':
            if (optarg != NULL)
                counter = atoi(optarg);
            printf("option --wide %d found!\n", counter);
            for (int i = 0; i < counter; i  )
                printf("Hello world\n");
            break;
         case 'o': /* and take the case into account */
                printf("option --wide-option found!\n");
            break;
        default:
            return 0;
        }
    }
    return 0;
}

  • Related