I am wondering why getopt_long() in the following code does not return ':' for missing values for the current defined options in my program. Also, when I would like to print optopt and opterr, it does not reflect the current status of my program. Thank you very much!
for(int i=optind;i<argc;++i)
{opt.read_files.push_back(argv[i]);}
if(verbose_flag)
{opt.verbose=true;}
}
bool check_options(program_options &opt)
{
bool success=true;
std::cerr<<std::endl;
if(opt.read_files.size()==0)
{std::cerr<<"--- no read files specified as inputs"<<std::endl;success=false;}
else
{
struct stat stat_file_info;
int int_stat;
std::vector<std::string>::const_iterator it;
for(it=opt.read_files.begin();it != opt.read_files.end();++it)
{
int_stat=stat(it->c_str(),&stat_file_info);
if(int_stat != 0)
{
std::cerr<<"--- error: file not found "<<*it<<std::endl;
success=false;
}//if
}//for
}//else
}
int main(int argc,char** argv)
{
program_options opt;
parse_options(argc,argv,opt);
if(!check_options(opt))
{
exit(1);
}
return 0;
}
when I use the command line like this:
./a.out -k 5 -s 6 /home/Documents/Data.txt it works fine
but when I use (missing argument value) :
./a.out -k 5 -s /home/Documents/Data.txt it sys:
no read files specified as inputs and it should be: " option with missing argument"
The parsing of command line argument should be like: k has integer value and s has integer value and any thing else it should be the name of the file. As you said /home/Documents/Data.txt is taken as the argument for -s which it should not because -s should be detected as missing argument value case ':' .
":k:s:"
you say that the -s option has one argument, you don't specify that it is a number (afaik, you can't do it)
getopt_long() gives you whatever follows -s as argument, in this case /home/Documents/Data.txt, it is your job to validate it (perhaps use strtol() instead of atoi())
If getopt_long() encounters an option character that was not in optstring ":k:s:", then '?' is returned. If getopt() encounters an option with a missing argument, then the return value depends on the first character in optstring ":k:s:" if it is ':', then ':' is returned;
This why I put : and it does not work in my code :-(