【发布时间】:2016-01-16 07:08:24
【问题描述】:
这是我第一个使用 getopt_long() 的程序,所以如果这个问题是微不足道的,请原谅我。
当传递给我的程序的第一个参数无效时,我遇到了问题
这是我的 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;
}
基本上如果我按以下方式启动我的程序
./myProgram a --rdonly file1.txt
程序不解析任何参数,跳过开关直接返回。
如果第一个参数以 - 或 -- 开头(即使它是一个错误的参数),程序会正确运行。
我该如何解决这个问题?
谢谢。
【问题讨论】:
标签: c getopt-long