Related library functions # include <unistd.h> #include <getopt.h>int getopt (int argc, char * const ARGV[],CONST char *optstring); extern char *optarg;extern int optind, Opterr, optopt;int getopt_long (int argc, char * const ARGV[],CONST Char *optstring, const struct Option *longopts, int *longindex); int getopt_long_only (int argc, char * const ARGV[],CONST Char *optstring,co NST struct option *longopts, int *longindex);
EG1:
#include <stdio.h> #include <getopt.h>int main (int argc,char *argv[]) { int opt; char *optstring = "A:b:c:de The; // represents the-A,-B,-C,-D,-E command line parameter, with the expression parameter with: can specify a value, so the de cannot specify a value of while (opt = Getopt (argc,argv,optstring)) != -1) { printf ("opt = %c\n ", opt); printf (" optarg = %s\n ", OPTARG); printf ("optind = %d\n", Optind); printf ("argv[optind-1] = %s\n\n", Argv[optind-1]); } return 0;} #./test_arg -a 1 -b 2 -c 3 -d -eopt = aoptarg = 1optind = 3argv[optind-1] = 1opt = boptarg = 2optind = 5argv[optind-1] = 2opt = coptarg = 3optind = 7argv[ optind-1] = 3opt = doptarg = (NULL) optind = 8argv[optind-1] = -dopt = eoptarg = (NULL) OPTIND&NBSP;=&NBSP;9ARGV[OPTIND-1]&NBSP;=&NBSP;-E
This article is from the "Programmer's Development Path" blog, so be sure to keep this source http://xwandrew.blog.51cto.com/2909336/1971684
C + + Parse command-line arguments