这是我第一个使用getopt_long()的程序,所以如果这个问题是微不足道的,请原谅我。
当传递给我的程序的第一个参数无效时,我遇到了问题
这是我的主代码
int main(int argc, char * argv[])
{
printf("----------------------------------------------nn");
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 %dn",overallExitStatus);
printf("----------------------------------------------nn");
return overallExitStatus;
}
基本上如果我通过以下方式启动我的程序
./myProgram a --rdonly file1.txt
程序不会通过任何参数解析,跳过开关并直接返回。
在第一个参数以 - 或 -- 开头的情况下(即使它是一个错误的参数),程序的行为正确。
如何解决此问题?
谢谢。
>a
是一个有效的非选项(位置)参数,所以这就是getopt_long假设的。
getopt_long选项字符串中的+
阻止选项参数的重新排序,因此它不会提前查看--rdonly
参数。即使您允许重新排序,a
也会被视为第一个位置参数。