The Pointer The Pointer - 1 month ago 12
C Question

The variable optarg of getopt()

I've read through the documentation for

, but I do not find the explanations of
optarg
clear.

I cannot find any other sources which explicitly and clearly explain general information about
optarg
.

I would appreciate it if someone could clarify and elaborate on the general information about
optarg
.

I would like to know:


  • What
    optarg
    is.

  • How
    optarg
    gets its value.

  • The documentation mentions something about colons changing the value of
    optarg
    .



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

Answer

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