Search code examples
ccommand-line-argumentsgetopt

getopt switch statement never hitting default case


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?


Solution

  • 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