Pergunta

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);
}
Foi útil?

Solução

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.

Outras dicas

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?

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top