我在C中使用getopt_long的时候遇到了一个问题,如描述的,结构如下:
struct option{
const char *name;
int has_arg;
int *flag;
int val;
};
如果设置了 flag,getopt_long 应该返回 0 并将 *flag 设置为 val。但在我的代码中,getopt_long return val 和 *flag 保持不变。代码如下:
#include<stdio.h>
#include<getopt.h>
int help;
int output;
int verbose;
const char *short_option = "ho:v";
const struct option long_options[] = {
{"help", 0, &help, 'h'},
{"output", 1, &output, 'o'},
{"verbose", 0, &verbose, 'v'},
{NULL, 0, NULL, 0}
};
void print_help()
{
printf("in option help: \n");
}
void print_output(char *content)
{
printf("in option output: argument is %s\n",content);
}
void print_verbose()
{
printf("in option verbose\n");
}
void print_args()
{
printf("help is %d\n",help);
printf("output is %d\n",output);
printf("verbose is %c\n",verbose);
}
int main(int argc, char **argv)
{
int next_option;
while( (next_option = getopt_long(argc, argv, short_option, long_options, NULL )) == 0)
{
printf("next_option is %c\n",next_option);
print_args();
}
return 0;
}
任何人都可以帮忙吗?