简体   繁体   中英

Problems using getopt in C

I wanted to use getopt() to parse arguments supplied at the command line, but I am having trouble with very simple test cases. I have the following code (which is almost, but not entirely identical, to that supplied as an example in the POSIX standard definition ).

int main(int argc, char *argv[]) {
    int c;
    int rmsflg = 0, saflg = 0, errflg = 0;
    char *ifile;
    char *ofile;

    //Parse command line arguments using getopt
    while (((c=getopt(argc,argv, ":i:rso:")) != 1) && (errflg == 0))  {
        switch(c){
            case 'i':
                ifile="optarg";
                break;
            case 'o':
                ofile="optarg";
                break;
            case 'r':
                if (saflg)
                    errflg++;
                else {
                    rmsflg++;
                    printf("Root Mean Square averaging selected\n");
                }
                break;
            case 's':
                if (rmsflg)
                    errflg++;
                else {
                    saflg++;
                    printf("Standard Arithmetic averaging selected\n");
                }
                break;
            case ':':
                fprintf(stderr,"Option -%c requires an argument\n",optopt);
                errflg++;
                break;
            case '?':
                fprintf(stderr,"Option -%c is not a valid option\n",optopt);
                errflg++;
                break;
            default:
                fprintf(stderr,"The value of c is %c,\
                        the option that caused this error is -%c\n",c,optopt);
                errflg++;
                break;  
        }
    }
    if (errflg) {
        fprintf(stderr, "usage: xxx\n");
        exit(2);
    }
    return 0;
}

Firstly, when I don't have the default case in there, nothing is output. When I inserted the default case, and make it output the value that c has, I get ? . This is odd for 2 reasons. Firstly, and this is what bothers me most, why doesn't c then match the ? case which was specifically written to match this output, but rather drops through to the default case. Secondly, the output of optopt is (for my input) o . The ? character is only returned if the option supplied does not match any character in optstring .

In the while loop condition you should check the return value of getopt against -1 not 1. Then if you pass the option -? on the command line, it should be recognized.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM