N
N
Nikita Kudinov2020-11-25 13:38:31
C++ / C#
Nikita Kudinov, 2020-11-25 13:38:31

How to process -- in getopt_long?

We need to process the input program -n 2 -t 4 -- text.
How can I get this text after --?
I have this code:

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

int main(int argc, char *argv[])
{
        struct option longopts[] =
        {
                {
                        .name = "number",
                        .has_arg = required_argument,
                        .flag = NULL,
                        .val = 'n'
                },
                {
                        .name = "timeout",
                        .has_arg = required_argument,
                        .flag = NULL,
                        .val = 't'
                },
                {
                        .name = "",
                        .has_arg = required_argument,
                        .flag = NULL,
                        .val = 0
        }
        };
        while (1)
        {
                int c = getopt_long(argc, argv, "n:t:", longopts, NULL);
                if (c == -1)
                {
                        break;
                }
                switch (c)
                {
                        case 'n':
                                printf("option 'n' with '%s'\n", optarg);
                                break;
                        case 't':
                                printf("option 't' with '%s'\n", optarg);
                                break;
            case NULL:
                                printf("def");
                                break;
                }
        }
        return 0;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2020-11-25
@Nikita_Kudinov

You can insert something like this after the while loop:

if (optind < argc) {
                int i;

                for (i = optind; i < argc; ++i)
                        printf("> %s\n", argv[i]);
        }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question