简体   繁体   中英

C, How is getopt() updating

I'm trying to make sense of a section of skeleton code for a class. The intended usage would be:

./a.out -d -n Foo -i Bar

The skeleton code works fine, but I have never used getopt() and can't understand why it works correctly (understanding it has nothing to do with the assignment, I just want to make sense of it). How is it that it updates / exits the while loop? I don't see a pointer increment or the arguments passed to it in the loop change at all.

char *optString = "-d-n:-i:";
int opt = getopt(argc, argv, optString);

while (opt != -1) {
    switch(opt) {
    case 'd':
        debug = 1;
        break;
    case 'n':
        nameserver_flag = 1;
        nameserver = optarg;
        break;
    case 'i':
        hostname = optarg;
        break;
    case '?':
        usage();
        exit(1);
    default:
        usage();
        exit(1);
    }
    opt = getopt(argc, argv, optString);
}

每次调用getopt都会处理argv中的一个参数,将结果返回到opt等等。还有什么可以理解的?

getopt uses global variables to store the argument index, the next character to parse and some other information. Each time you call getopt , the function checks these variables to know where it last was (or where you told it it was) and updates the variables for the next call.

Most importantly, optind stores the index in argv of the next element to be scanned.

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