Question

I've got the following code and I'm unsure how to add optional arguments for file locations after the -arguments when running from command line. I've been doing a lot of reading but I'm just finding it confusing. Here is the code as it currently stands.

int c;
while ((c = getopt(argc, argv, "vdras")) != EOF) {
    switch (c) {
        case 'v': v = true;
            break;
        case 'd': d = true;
            break;
        case 'r' : r = true;
            break;
        case 'a' : a = true;
            break;
        case 's' : s = true;
            break;
    }
}
argc -= optind;
argv += optind;

What I need to be able to do now is add in a file at the end of all these commands (or a subset of those commands).

As such I could type -rda filehere or -a filehere or just filehere as valid arguments for the program.

I've been reading THIS link which leads me to believe putting double semi-colons between all of the command line options, thus it will look like:

while ((c = getopt(argc, argv, "::v::d::r::a::s::")) != EOF) {

would allow me to specify optional arguments after the conditions however I don't know how to capture them. As in, I've been trying to make cases whereby I enter in a random file name and have it print out some test code just so I know that it's working but I can't seem to get it right. I'm wondering if I need to somehow incorporate *optarg into my switch which will allow me to get any arguments following the options but I'm not really sure how to go about this. Any explanation would be great.

Was it helpful?

Solution

Did you read the man page? The option argument, if there is one, will be in the global variable optarg.

Even the link you have there says the same. Your option string doesn't need the leading :: either - only the ones after the letters mean anything.

Edit: Here's a complete working example of what it looks like you're trying to do:

#include <unistd.h>
#include <iostream>

int main(int argc, char **argv)
{
    int ch;

    while ((ch = getopt(argc, argv, "v:")) != -1)
    {
        switch (ch)
        {
            case 'v':
                std::cout << optarg << std::endl;
                break;
        }
    }
    return 0;
}

And output:

$ ./example -v abcde
abcde
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top