C getopt
c getopt example
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
void parse_options(int argc, char *argv[])
{
static struct option long_options[] = {
{"version", no_argument, 0, 'v'},
{"quiet", no_argument, 0, 'q'},
{"wait", required_argument, 0, 'W'},
{0, 0, 0, 0},
};
static const char *options_string = "vqhW:";
int c, i;
int option_index = 0;
optind = 1; // reset getopt
while (1) {
c = getopt_long(argc, argv, options_string, long_options,
&option_index);
// no more options
if (c == -1)
break;
switch (c) {
case 'v':
printf("progress version %s\n", PROGRESS_VERSION);
exit(EXIT_SUCCESS);
break;
case 'q':
printf("hit q\n");
break;
case 'W':
printf("hit W %s\n", optarg);
break;
case 'h':
printf("help %s\n", argv[0]);
exit(EXIT_SUCCESS);
break;
case '?':
default:
exit(EXIT_FAILURE);
}
}
if (optind < argc) {
fprintf(stderr, "Invalid arguments.\n");
exit(EXIT_FAILURE);
}
}
int main(int argc, char const *argv[])
{
parse_options(argc, argv);
return 0;
}
可支援多次
./opt -W 1 -W 2 -W 3
hit W 1
hit W 2
hit W 3