0

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.

4

1 回答 1

1

你读过手册页吗?选项参数(如果有的话)将在全局变量optarg中。

即使你在那里的链接也说同样的话。您的选项字符串也不需要前导::- 只有字母后面的那些才有意义。

编辑:这是一个完整的工作示例,说明您正在尝试执行的操作:

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

并输出:

$ ./example -v abcde
abcde
于 2013-06-12T00:50:16.863 回答