void parse_options(int argc, char *argv[]) { int c; // parameters for getopt_long() function static const char short_options[] = "AHSh:dif:v"; static const struct option long_options[] = { {"help", no_argument, NULL, 1 }, {"all", no_argument, NULL, 'A'}, {"hash", required_argument, NULL, 'h'}, {"format", required_argument, NULL, 'f'}, {"version", no_argument, NULL, 'v'}, { NULL, 0, NULL, 0 } }; // setting all fields to false memset(&config, false, sizeof(config)); config.all = true; while ((c = getopt_long(argc, argv, short_options, long_options, &ind))) { if (c < 0) break; switch (c) { case 1: // --help option usage(); exit(EXIT_SUCCESS); case 'A': config.all = true; break; case 'v': printf("%s %s\n%s\n", PROGRAM, TOOLKIT, COPY); exit(EXIT_SUCCESS); case 'h': config.all = false; parse_hash_algorithm(optarg); break; case 'f': parse_format(optarg); break; default: fprintf(stderr, "%s: try '--help' for more information\n", PROGRAM); exit(EXIT_FAILURE); } } }
static options_t *parse_options(int argc, char *argv[]) { options_t *options = malloc_s(sizeof(options_t)); memset(options, 0, sizeof(options_t)); // parameters for getopt_long() function static const char short_options[] = "f:a:h:s:v"; static const struct option long_options[] = { { "help", no_argument, NULL, 1 }, { "format", required_argument, NULL, 'f' }, { "algorithm", required_argument, NULL, 'a' }, { "header", required_argument, NULL, 'h' }, { "section-name", required_argument, NULL, 's' }, { "section-index", required_argument, NULL, 2 }, { "version", no_argument, NULL, 'v' }, { NULL, 0, NULL, 0 } }; // Default options. options->algorithms.all = true; options->headers.all = true; options->all = true; int c, ind; while ((c = getopt_long(argc, argv, short_options, long_options, &ind))) { if (c < 0) break; switch (c) { case 1: // --help option usage(); exit(EXIT_SUCCESS); case 'f': if (output_set_format_by_name(optarg) < 0) EXIT_ERROR("invalid format option"); break; case 'a': options->algorithms.all = false; parse_hash_algorithm(options, optarg); break; case 's': options->all = false; options->headers.all = false; // TODO: How do we need to handle non-ascii names? options->sections.name = strdup(optarg); break; case 2: options->all = false; options->headers.all = false; options->sections.index = strtol(optarg, NULL, 10); if (options->sections.index < 1 || options->sections.index > MAX_SECTIONS) { EXIT_ERROR("Bad argument for section-index,"); } break; case 'v': printf("%s %s\n%s\n", PROGRAM, TOOLKIT, COPY); exit(EXIT_SUCCESS); case 'h': options->all = false; options->headers.all = false; parse_header_name(options, optarg); break; default: fprintf(stderr, "%s: try '--help' for more information\n", PROGRAM); exit(EXIT_FAILURE); } } // TODO: Warn about simultaneous usage of -h, -s, and --section-index. return options; }