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 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.

其他提示

Each call to getopt processes one more of the arguments in argv, returning the result in opt, etc. etc. What else is there to understand?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top