The Pointer
The Pointer

Reputation: 2386

The variable optarg of the function getopt()

I've read through the documentation for the function getopt(), but I do not find the explanations clear, especially with regards to the variable optarg. I cannot find any other sources that explicitly and clearly explain general information about optarg. My questions are as follows:

The documentation has examples of how to use optarg, but I am more so interested in clear and elaborate explanations of the variable itself.

Upvotes: 3

Views: 2979

Answers (1)

Sourav Ghosh
Sourav Ghosh

Reputation: 134346

The man page says, (emphasis mine)

optstring is a string containing the legitimate option characters. If such a character is followed by a colon, the option requires an argument, so getopt() places a pointer to the following text in the same argv-element, or the text of the following argv-element, in optarg. Two colons mean an option takes an optional arg; if there is text in the current argv-element (i.e., in the same word as the option name itself, for example, "-oarg"), then it is returned in optarg, otherwise optarg is set to zero. [...]

and the given code snippet below shows the usage.

while ((opt = getopt(argc, argv, "nt:")) != -1) {
    switch (opt) {
    case 'n':
        flags = 1;
        break;
    case 't':
        nsecs = atoi(optarg);
        tfnd = 1;
        break;
    default: /* '?' */
        fprintf(stderr, "Usage: %s [-t nsecs] [-n] name\n",
                argv[0]);
        exit(EXIT_FAILURE);
    }
}

To elaborate, by seeing the syntax "nt:" we can understand that the option n does not need any argument but option t will have a following argument to it. So, when the option t is found, the corresponding argument is stored into optarg and can be retrieved by accessing optarg.

So, basically, getopt() will return the option and optarg will return the supplied argument for that option, if any.

In case the binary is run like ./a.out -t 30, then when getopt() returns t, optarg will be holding a pointer to a string containing 30 (not an int, mind it).

Upvotes: 5

Related Questions