Created
November 2, 2016 17:51
-
-
Save jampajeen/9c04b117da6c69becb861866179bac31 to your computer and use it in GitHub Desktop.
console app option in C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <getopt.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#define OPT1 "Operation1" | |
#define OPT2 "Operation2" | |
struct global_args_t { | |
const char *program_name; | |
const char *config_file; | |
const char *operation_name; | |
int verbose; | |
} _args; | |
void print_usage(FILE* stream, int exit_code) { | |
fprintf(stream, "Usage: %s -o <operation name> [other options] \n", _args.program_name); | |
fprintf(stream, | |
" -h --help Display usage information.\n" | |
" -o --operation name Run operation name (\"" OPT1 "\", \"" OPT2 "\").\n" | |
" -c --config filename Run with configuration file.\n" | |
" -v --verbose Print verbose messages.\n"); | |
exit(exit_code); | |
} | |
void select_option(int argc, char* argv[]) { | |
int next_option; | |
const char* const short_options = "ho:c:v"; | |
const struct option long_options[] = { | |
{ "help", no_argument, NULL, 'h'}, | |
{ "operation", required_argument, NULL, 'o'}, | |
{ "configure", required_argument, NULL, 'c'}, | |
{ "verbose", no_argument, NULL, 'v'}, | |
{ NULL, no_argument, NULL, 0} | |
}; | |
_args.config_file = NULL; | |
_args.operation_name = NULL; | |
_args.verbose = 0; | |
_args.program_name = argv[0]; | |
do { | |
next_option = getopt_long(argc, argv, short_options, long_options, NULL); | |
switch (next_option) { | |
case 'o': | |
_args.operation_name = optarg; | |
break; | |
case 'c': | |
_args.config_file = optarg; | |
break; | |
case 'v': | |
_args.verbose = 1; | |
break; | |
case 'h': | |
case '?': | |
print_usage(stdout, 0); | |
case -1: /* Done with options. */ | |
break; | |
default: /* Something else: unexpected. */ | |
exit(EXIT_FAILURE); | |
} | |
} while (next_option != -1); | |
if (argc < 2 || _args.operation_name == NULL) { | |
print_usage(stdout, 0); | |
} | |
// remained arguments | |
if (_args.verbose) { | |
for (int i = optind; i < argc; ++i) { | |
printf("Argument: %s\n", argv[i]); | |
} | |
} | |
if(strcmp(_args.operation_name, OPT1) == 0) { | |
printf("operation: %s\n",_args.operation_name); | |
} else if(strcmp(_args.operation_name, OPT2) == 0) { | |
printf("operation: %s\n",_args.operation_name); | |
} else { | |
printf("Unknown operation\n"); | |
print_usage(stdout, 0); | |
} | |
} | |
int main(int argc, char* argv[]) { | |
select_option(argc, argv); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment