Getopt () Analysis of command line parameters
int getopt (int argc, char *const argv[], const char *optstring);
Given the number of command arguments (ARGC), the array of these arguments (argv), and the option string (optstring), getopt () returns the first option and sets some global variables. When the function is called again with the same parameter, it returns the next option and sets the corresponding global variable. If there is no longer a recognized option, it returns-1, and the task is complete. Getopt () can be called repeatedly until it returns-1.
The global variables set by getopt () include:
optarg--A pointer to the current option parameter, if any.
optind--the index of the next argv pointer when Getopt () is called again.
optopt--Last known option.
Where the optstring writing format is as follows: "F:e:ac", where ': ' means the previous character is a parameter
Example:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main (int argc, char *argv[]) {
int o;
extern int Optind, optopt, Opterr;
extern char *optarg;
Opterr = 0;
while ((o = getopt (argc, argv, "f:e:a"))!=-1) {
Switch (o) {
Case ' F ':
fprintf (stderr, "F%s \ n", Optarg);
Break
Case ' E ':
fprintf (stderr, "e%s\n", optarg);
Break
Case ' a ':
fprintf (stderr, "a%s\n", optarg);
Break
Case '? ':
if (optopt = = ' F ' optopt = = ' E ')
fprintf (stderr, "option-%c requires an argument.\n", optopt);
else if (Isprint (optopt))
fprintf (stderr, "Unknown option '-%c '. \ n", optopt);
Else
fprintf (stderr, "Unknown option character ' \\x%x '. \ n", optopt);
return 1;
Default
printf ("Unknown option Characte");
Abort ();
}
}
}
It is to be noted that:
Variable optind, optopt, Opterr, optarg are all global variables, external references, which need to be defined with "extern"
"F:e:a" means that the-F and-e have parameters,-A has no parameters, compiles to test, and tests
#/test-a ' abc '-f ' abc '-e ' abc '
A (NULL)
F ABC
E ABC
#./test-a ' abc '-f ' abc '-e
A (NULL)
F ABC
OPTION-E requires an argument.
However, such code is still problematic, if "-f" after the lack of parameters, it will mistakenly put "-e" as "F" parameter
#./test-a ' abc '-F-E ' abc '
A (NULL)
F-e
This article links http://www.cxybl.com/html/net/winform/20120610/29307.html