WolvenOmega WolvenOmega - 2 months ago 27
C Question

Optopt and getopt in C

I'm trying to figure out

getopt
, but I keep getting hung up at the end of the switch statement.

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int
main (int argc, char **argv)
{
int aflag = 0;
int bflag = 0;
char *filename = NULL, *x = NULL;
int index;
int c;

opterr = 0;
while ((c = getopt (argc, argv, "hnc:")) != -1)
switch (c)
{
case 'h':
printf("You chose h");
break;
case 'n':
x = optarg;
break;
case 'l':
filename = optarg;
break;
case '?':
if (optopt == 'n' || optopt == 'l')
fprintf (stderr, "Option -%c requires an argument.\n", optopt);
else if (isprint (optopt))
fprintf (stderr, "Unknown option `-%c'.\n", optopt);
else
fprintf (stderr,
"Unknown option character `\\x%x'.\n",
optopt);
return 1;
default:
abort ();
}

for (index = optind; index < argc; index++)
printf ("Non-option argument %s\n", argv[index]);
return 0;
}


When I compile this and run
a.out -l
it does as it should, but when I do
a.out -n
it does nothing, when it should say "Option n requires an argument."

How can I fix this?

Answer

Your optstring "hnc:" says n is a valid argument that doesn't require an argument, while l is not specified at all so the ? case will always be hit. Try using

getopt (argc, argv, "hn:l:")

which says n and l both require arguments.

Comments