The getopt () function is used to analyze command line parameters. Its function prototype and related variables are declared as follows:
# Include
Extern char * optarg;
Extern int optind, // The initialization value is 1. When getopt is called next time, check the option again from the position of optind storage, that is, starting from the next '-' option.
Extern int opterr, // The initialization value is 1. When opterr is set to 0, getopt does not output an error message to stderr.
Extern int optopt; // when the command line option character is not included in optstring or the option lacks necessary parameters, this option is stored in optopt, and getopt returns '? '.
Int getopt (INT argc, char * const argv [], const char * optstring );
Optarg and optind are two of the most important external.
Variable. Optarg is a pointer to a parameter (of course this is only for options with parameters); optind is the index of the argv [] array. As we all know, argv [0] Is the function name, all parameters from argv [1]
So optind is initialized to 1. Each time you call the getopt () function, an option is returned. If this option has a parameter, optarg points to this parameter.
-1 is returned when the option parameter in the command line does not check the option contained in optstring.
The getopt () function has three parameters. argc and argv [] do not need to be mentioned. The optstring is a list of optional strings.
The getopt () function considers optstring '-
'(Note! Not a string !!) It is the command line parameter option. Some Parameter options can be followed by the parameter value. The format specifications in optstring are as follows:
1) single character, indicating options,
2) A single character followed by a colon ":", indicating that this option must be followed by a parameter value. Parameters are immediately followed by options or separated by spaces. The pointer of this parameter is assigned to optarg.
3) a single character is followed by two colons (:), indicating that this option must be followed by a parameter.
Parameters must be followed by no space. The pointer of this parameter is assigned to optarg. (This feature is a GNU extension ).
# Include <br/> # include </P> <p> int main (INT argc, char * argv []) <br/>{< br/> int ch; <br/> opterr = 0; </P> <p> while (CH = getopt (argc, argv, "A: B: CDE "))! =-1) <br/>{< br/> printf ("/n"); <br/> printf ("optind: % d/N ", optind); <br/> printf ("optarg: % s/n", optarg); <br/> printf ("ch: % C/N", CH ); <br/> switch (CH) <br/> {<br/> case 'A': <br/> printf ("Option A: '% s'/N ", optarg); <br/> break; <br/> case 'B': <br/> printf ("Option B: '% s'/N", optarg ); <br/> break; <br/> case 'C': <br/> printf ("option C/N"); <br/> break; <br/> case 'D': <br/> printf ("option D/N"); <br/> break; <br/> case 'E ': <br/> printf ("option E/N"); <br/> break; <br/> default: </P> <p> printf ("other option: % C/N ", CH); <br/>}< br/> printf (" optopt + % C/N ", optopt ); <br/>}< br/>