WolvenOmega WolvenOmega - 11 months ago 86
C Question

Optopt and getopt in C

I'm trying to figure out

, 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>

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");
case 'n':
x = optarg;
case 'l':
filename = optarg;
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);
fprintf (stderr,
"Unknown option character `\\x%x'.\n",
return 1;
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 Source

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.