using getopt_long
- man 3 getopt long
- handling unknown parameter
- handling parameter in optarg
- switch off error message of unknown parameter
#include
#include
#include
void help_option_handling()
{
printf("\n help text:\n");
}
void handle_user_option( char *fname)
{
printf("\nprocessing user file : %s\n", fname);
}
void handle_version_info()
{
printf("\nThis is version 0.1\n");
}
void handle_not_supported_option()
{
printf("\nnot supported option: %c\n", optopt);
}
void handle_unhandled_option()
{
printf("\n not handled option: %s\n", optarg);
}
int main(int argc, char* argv[])
{
int get_opt = -1;
static struct option my_long_option[]=
{
{"user", required_argument, NULL, 'u'},
{"verbose", no_argument, NULL, 'v'},
{"Version", no_argument,NULL, 'V'},
{"help", no_argument,NULL, 'h'},
{ NULL, 0, NULL, 0 }
};
char my_short_options[] = "+u:Vvh";
int option_index;
int verbose_mode = 0;
int original_opterr = opterr;
opterr = 0; //to prevent error messages
while (1)
{
get_opt = getopt_long( argc,
argv,
my_short_options,
my_long_option,
&option_index );
if (get_opt == -1)
{
break;
}
switch (get_opt)
{
case 'h':
help_option_handling();
break;
case 'u':
handle_user_option( optarg );
break;
case 'v':
verbose_mode = 1;
opterr = original_opterr;
break;
case 'V':
handle_version_info();
break;
case '?':
//the unsupported option handling
handle_not_supported_option();
break;
case '1':
handle_unhandled_option();
break;
}
}
return 0;
}