Monday, October 17, 2011

C - parsing command line options with getopt


Very useful way to parse the command line options in C/C++:


void usage(){
std::cout << "Usage: Program.exe [options] inputFile" << std::endl;
std::cout << "Options are:" << std::endl;
std::cout << "-n x : read only n entries" << std::endl;
std::cout << "-o FILE: set output file" << std::endl;
}

int main(int argc, char* argv[]){

std::string outputFileName;
int nEvents = -1;

//Parse options from the command line
for(;;){
//Get option
int c = getopt(argc, argv, "n:o:");

//If end of options break...
if (c<0) break;

switch(c){

case 'n':{
nEvents = atoi(optarg);

std::cout << "Number of entries to read : " << nEvents << std::endl;
break;
}

case 'o':{
//std::cout << "Optarg:" << optarg << std::endl;
outputFileName = std::string(optarg);

std::cout << "Output filename is : " << outputFileName << std::endl;
break;
}

case '?':{
usage();
exit(0);
}//end of case

}//end of switch
}//end of for loop

if((argc - optind) < 1){
usage();
exit(1);
}
}

No comments:

Post a Comment