Search code examples
cgetopt

getopt to take only one argument


I have a question about getopt in C. I have multiple option flags and am trying to get it to take one argument for everything. The command line will look something like command -a fileName or command -b fileName or command -ab fileName. Basically every command takes in one fileName and if they want to combine commands they should only have to type in one fileName. In getopt the string looks like a:b: and a variable is set to argv[argc -1]. This is fine if it's just one option but fails if there are multiple options (ie command -ab fileName) since : forces users to input an option but :: will make the singe options not force the user to type in an option. Any suggestions?


Solution

  • The optind global variable lets you know how many of the argv strings were used. So one way to approach this problem is to just drop the colons, and use a string like "ab". Here's an example of what the code looks like (adapted from the example in the man page):

    int main(int argc, char *argv[])
    {
        int ch;
        while ((ch = getopt(argc, argv, "ab")) != -1)
        {
            if (ch == 'a')
                printf("Got A\n");
            else if (ch == 'b')
                printf("Got B\n");
            else
                printf("Got confused\n");
        }
    
        if (optind != argc-1) 
            printf("You forgot to enter the filename\n");
        else
            printf("File: %s\n", argv[optind]);
    }
    

    If you run this with a command line like

    ./test -ab hello
    

    the output is

    Got A
    Got B
    File: hello