Taken directly from the GNU C Library Reference page on getopt
:
while ((c = getopt (argc, argv, "abc:")) != -1)
switch (c)
{
case 'a':
aflag = 1;
break;
case 'b':
bflag = 1;
break;
case 'c':
cvalue = optarg;
break;
case '?':
if (optopt == 'c')
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();
}
c
here is the argument that takes an optional parameter, so this is probably the syntax you were looking for.
What I understand getopt
does is loop through the given arguments, parsing them one at a time. So when it gets to the option c
(in your case p
) where a second argument is required, it is stored in optarg
. This is assigned to a variable of your choice (here cvalue
) for later processing.
1
solved getopt adding extra functionality in C