i am making a program in c that accepts command line arguments like --version , --download.
when i do this :
$program --version --download file
the program outputs the version and downloads the file. But when i do this:
$program --download --version file
the program considers --version
to be the argument to --download
.
I have used getopt_long()
function for parsing the command line arguments. Here's a snippet from my code:
while ((ch = getopt_long(argc, argv, "d:g:hv", longoptions, &optindex)) != -1 )
{
switch(ch)
{
case 'd' :
if ( optarg )
printf("Downloading %s...\n" , optarg);
iso(optarg);
break ;
case 'g' :
if ( optarg )
printf("Downloading glug-mirror automation script for %s ...\n", optarg);
getscript(optarg);
break ;
case 'v' :
printf("glug version 1.0.0 ( NIT Hamirpur)\n");
break ;
case 'h' :
usage(status);
break ;
default :
status = 2 ;
usage(status);
}
}
getoptlong()
is doing exactly what it is supposed to do."d:g:hv"
implies that the parametersd
andg
require a value.You should run your program as
Checkout this detailed example demonstrating the various aspects of using
getoptlong()
.Apparently because
rm
's parameters (r
,v
etc.) do NOT accept any values as arguments. Thusdirectory
does not get passed to any of them but rather is a separate cmd-line argument on its own. You can confirm this from the source-code of rm.To do something similar for your program, you will need to modify the optstring to
"dghv"
and handle the parameter"file"
separately.