Created
January 28, 2015 16:41
-
-
Save josephwb/5c98e40ab2cba892c35b to your computer and use it in GitHub Desktop.
getopt_long: hack to read in an arbitrary number of arguments for a single option
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Compile with: | |
* g++ -Wall -std=c++11 dummy.cpp -o dummy -O | |
* Run as: | |
* ./dummy -s *.txt | |
*/ | |
#include <iostream> | |
#include <string> | |
#include <fstream> | |
#include <vector> | |
#include <string.h> | |
#include <getopt.h> | |
using namespace std; | |
void print_help() { | |
cout << "Dummy help." << endl; | |
} | |
string versionline("fakety fakety fakety fake."); | |
static struct option const long_options[] = | |
{ | |
{"seqf", required_argument, NULL, 's'}, | |
{"outf", required_argument, NULL, 'o'}, | |
{"help", no_argument, NULL, 'h'}, | |
{"version", no_argument, NULL, 'V'}, | |
{NULL, 0, NULL, 0} | |
}; | |
int main(int argc, char * argv[]) { | |
bool fileset = false; | |
vector <string> inputFiles; | |
string outf = ""; | |
while (1) { | |
int oi = -1; | |
int curind = optind; | |
int c = getopt_long(argc, argv, "s:o:hV", long_options, &oi); | |
if (c == -1) { | |
break; | |
} | |
switch(c) { // hack to read in an arbitrary number of arguments for a single option | |
case 's': | |
fileset = true; | |
curind = optind - 1; | |
while (curind < argc) { | |
string temp = strdup(argv[curind]); | |
curind++; | |
if (temp[0] != '-') { | |
ifstream infile(temp.c_str()); | |
if (infile.good()) { // check that file exists | |
inputFiles.push_back(temp); | |
infile.close(); | |
} else { | |
cout << "Cannot find input file '" << temp << "'. Exiting." << endl; | |
exit(0); | |
} | |
} else { | |
optind = curind - 1; | |
break; | |
} | |
} | |
break; | |
case 'o': | |
outf = strdup(optarg); | |
break; | |
case 'h': | |
print_help(); | |
exit(0); | |
case 'V': | |
cout << versionline << endl; | |
exit(0); | |
default: | |
cout << "Exiting." << endl; | |
exit(0); | |
} | |
} | |
if (fileset) { | |
for (int i = 0; i < (int)inputFiles.size(); i++) { | |
cout << "File #" << i << ": " << inputFiles[i] << endl; | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment