getopt switch statement never hitting default case

2019-05-31 08:01发布

问题:

I've tried searching and haven't found a duplicate/similar question.

How come "default" is never triggering in this case? Working on some previous homework assignments for a course to prepare for the fall, and I'm having an issue with getopt() in C.

Here are the particular lines in question:

while ((c = getopt(argc, argv, "i:o:")) != -1) {
        switch (c) {
            case 'i':
            inFile = strdup(optarg);
            break;

            case 'o':
            outFile = strdup(optarg);
            break;

            default:
            usage(); //this prints the "usage" statement and exits cleanly.
        }
    }

My issue is, how come calling

./fastsort a b c d

doesn't print the usage and exit?

回答1:

The below code will search for options like -i hello or/and -o world

while((c = getopt(argc, argv, "i:o:") != -1)

However what you are executing is:

./fastsort a b c d

where getopt(argc, argv, "i:o:") != -1 is not satisfied since none of the passed argument a b c dis an option



回答2:

I figured it out, and feel like an idiot:

Since there are never any valid arguments/flags given, the while loop doesn't even execute. I just added a little check beforehand, and it seemed to fix things:

//Check number of args
if(argc < 5 || getopt(argc, argv, "i:o:") == -1){
    usage();
}

Edit: Just realized it's not quite yet working. Now, since I'm calling getopt once too soon, it's dumping one of the args prematurely, thus not setting correct ones properly.

My new "solution" (albeit a bit hacky) is:

-Initialize inFile and outFile to null
-Do the while loop as in my original post
-If inFile or outFile are still null, print usage

And it passed all of the automated tests given.