-1

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;
}
Mike
  • 4,041
  • 6
  • 20
  • 37
Kuttubek
  • 3
  • 4

1 Answers1

0

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;
}

Mathieu
  • 8,840
  • 7
  • 32
  • 45
  • in that case i want to implement "--number-nonblank". в этом случае я хочу реализовать опцию -b и --number-nonblank – Kuttubek Nov 10 '22 at 12:04
  • @Kuttubek Your questions are not clear, it's kinda hard to understand what exactly you want to achieve. If you want to implement as per your last comment, then add this into option struct: `{"number-nonblank", no_argument, NULL, 'b'},`, then program will accept `--number-nonblank` (and `-b`, which will be a short alternative for `--number-nonblank`, but will give the same result). – Andrejs Cainikovs Nov 10 '22 at 12:26
  • 1
    why the stddef.h library was included? – Kuttubek Nov 10 '22 at 12:47