问题描述:

This is my first program that uses getopt_long() so please excuse me if this questions is trivial.

I am having a problem when the first argument passed to my program is invalid

Here is my code for main

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

{

printf("----------------------------------------------\n\n");

int fd[128];

int fdCount=0;

int c;

int digit_optind =0;

int verboseFlag=0;

//to exit with this specific value collected from all functions

int overallExitStatus=0;

while(1)

{

int this_option_optind = optind ? optind : 1;

int option_index =0;

static struct option long_options[] = {

{"rdonly", optional_argument, 0, 'a'},

{"wronly", optional_argument, 0, 'b'},

{"command", optional_argument, 0, 'c'},

{"verbose", no_argument, 0, 'd'},

{0,0,0,0}

};

c=getopt_long(argc,argv, "+", long_options, &option_index);

if(c == -1)

break;

switch(c) {

case 'a':

rdonly(fd,&fdCount,verboseFlag,&optind,argc,argv);

break;

case 'b':

wronly(fd,&fdCount,verboseFlag,&optind,argc,argv);

break;

case 'c':

overallExitStatus +=command(fd,&optind,optarg,argc,argv,verboseFlag);

break;

case 'd':

verboseFlag=1;

break;

case '?':

break;

default:

printf("?? getopt returned character code 0%o ??\n", c);

}

}

printf("Program is finished exiting with status %d\n",overallExitStatus);

printf("----------------------------------------------\n\n");

return overallExitStatus;

}

basically if I start my program in the following way

./myProgram a --rdonly file1.txt

the program does not parse trough any arguments, skips the switch and goes straight to return.

in a case when the first argument starts with - or -- (even if it is a wrong argument) the program behaves correctly.

How can I fix this issue ?

thank you.

网友答案:

a is a valid non-option (positional) argument, so that's what getopt_long assumes it is.

The + in the getopt_long options string prevents reordering of option arguments, so it doesn't look ahead to the --rdonly argument. Even if you had allowed reordering, the a would be treated as the first positional argument.

相关阅读:
Top