getopt value stays null

Viewed 12447

I am passing my program inputs and I could see them in argv but getopt doesnt seem to have the argument that I expect.

This is how I run my prog: ./my_prog -X -f filename

<snip>
while ((opt = getopt(argc, argv, "Xf:eE:dD")) != EOF) {
    switch (opt) {
       case 'X':
       case 'f':
                if (optarg == NULL)
                fput("no point of living", fp);         << for debugging

</snip>

I always get optarg as null. WHY?

4 Answers

For who else get to this page: From http://www.gnu.org/software/libc/manual/html_node/Using-Getopt.html#Using-Getopt: An option character in this string can be followed by a colon (‘:’) to indicate that it takes a required argument. If an option character is followed by two colons (‘::’), its argument is optional; this is a GNU extension.

so in your argument you might use: "X:f:e:E:d:D:"

Had the same problem.

I know this is old but I recently noticed changed behaviour in the way I used to use getopt years ago. Maybe it was a different environment but I find using it today requires the optarg to be DIRECTLY after the flag (no space) otherwise optarg is null.

Using your example, replace ./my_prog -X -f filename with ./my_prog -X -ffilename

I find that works fine even though it feels wrong. Hope this helps someone else out later. Make sure to try it both ways.

Related