C 使用二进制掩码解析选项
晚上好!我目前正在为linux创建一个可执行文件。但是,在解析可执行文件的选项时,我遇到了错误 我不明白为什么“-p”选项通过了验证条件 我的项目的头文件:C 使用二进制掩码解析选项,c,C,晚上好!我目前正在为linux创建一个可执行文件。但是,在解析可执行文件的选项时,我遇到了错误 我不明白为什么“-p”选项通过了验证条件 我的项目的头文件: # define O_LONG 0x6c // -l # define O_RECUR 0x52 // -R # define O_ALL 0x61 // -a # define O_SORT 0x72 // -r # define O_R_SORT 0x74 //
# define O_LONG 0x6c // -l
# define O_RECUR 0x52 // -R
# define O_ALL 0x61 // -a
# define O_SORT 0x72 // -r
# define O_R_SORT 0x74 // -t
# define O_MSK_LONG 1
# define O_MSK_REC 2
# define O_MSK_ALL 4
# define O_MSK_SORT 8
# define O_MSK_R_SORT 16
解析选项的My函数:(option
->number X程序参数,options
是指向我的结果的指针)
“r”是
0x72
,而“p”是0x70
,因此如果flag=0x70
,那么flag&O_SORT
=0x70&0x72
=0x70
=flag
。您应该将条件修改为if(flag==O_SOMETHING){…}
为什么不O_LONG==flag
?请创建一个。此外,您的代码不会跳过空格。
int parse_option(int *options, char *option)
{
char flag;
option++; // To pass the first character -
while ((flag = *(char*)option))
{
if ((O_ALL & flag) == flag)
*options |= O_MSK_ALL;
else if ((O_RECUR & flag) == flag)
*options |= O_MSK_REC;
else if ((O_SORT & flag) == flag)
*options |= O_MSK_SORT;
else if ((flag & O_R_SORT) == flag)
*options |= O_MSK_R_SORT;
else if ((O_LONG & flag) == flag)
*options |= O_MSK_LONG;
else {
printf("command: invalid option -- '%c'\n", flag);
return (-1);
}
printf("%c %i\n", flag, *options);
option++;
}
return (1);
}