James Wilks
James Wilks

Reputation: 740

GetOpt Long recognizing Verbose

Right now, I'm trying to get my program to correctly regonize the flags i pass to it in the command line. The following commandline ./MineEscape --container BINARY infile.txt works correctly given that MineEscape is the name of the executable. However, I'm having an issue getting this command line to work, ./MineEscape --verbose 15 -c PAIRING infile.txt > outfile.txt

Also note that the required flags of the command line is --container and a type of container such as PAIRING or BINARY. As well as --verbose should be followed by an integer.

When running the incorrect command line, I'm having a problem with the verbose part, saying that there's a segfault.

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


struct arguments{
    bool binary;
    bool poorMan;
    bool sorted;
    bool pairing;
    int outputStatistics;
} choice;

const struct option longOpts[]{
    {"help",optional_argument,NULL,'h'},
    {"container",required_argument,NULL,'c'},
    {"verbose",optional_argument,NULL,'v'}
};

stringstream ss;

int opt=0,longIndex=0;
opt=getopt_long(argc,argv,"v:c:h",longOpts,&longIndex);
while(opt!=-1){
    switch(opt){
        case 'h':
            //Print out description of executable

            exit(0);
            break;
        case 'c':
            if(!strcmp("BINARY",optarg))
                choice.binary=1;
            else if(!strcmp("POOR_MAN",optarg))
                choice.poorMan=1;
            else if(!strcmp("SORTED",optarg))
                choice.sorted=1;
            else if(!strcmp("PAIRING",optarg))
                choice.pairing=1;
            else{
                ss<<"Sorry, not a valid container implementation\n";
                cout<<ss.str();
                exit(0);
            }
            break;
        case 'v':
            if(atoi(optarg)>0)
                choice.outputStatistics=atoi(optarg);
            else{
                ss<<"Sorry, requires a value greater than 0\n";
                cout<<ss.str();
                exit(0);
            }
            break;
        default:

            break;
    }
    opt=getopt_long(argc,argv,"v:c:h",longOpts,&longIndex);
}
}

Upvotes: 0

Views: 694

Answers (1)

user2711811
user2711811

Reputation:

You'll find 'optarg' has a value of NULL, despite that it was specified as "v:".

I found if "-v3" or "-v 3" is used, for example, that parses ok. But "--verbose 3" fails and "--verbose=3" works.

Oddly enough, this behaviour only seems to be with optional arguments.

This link has more

gcc 4.4.6

Upvotes: 1

Related Questions