1. Basic instructions
The function Description getopt () is used to parse command-line arguments. The parameters argc and argv are the number and contents of the arguments passed by main (). The parameter optstring is an option string that tells Getopt () which option to handle and which option requires parameters, and if the letter in the option string is followed by the colon ":", then there are related arguments, and the global variable Optarg points to this extra parameter. If you encounter other options that do not conform to optstring specified during processing getopt () displays an error message and sets the global variable Optarg to "?". Character, if you do not want getopt () to print error messages, simply set the global variable Opterr to 0.
2. Basic Information getopt (Analysis command line arguments) related function header file #include <unistd.h> define function int getopt (int argc,char * CONST argv[],const char * optstrin g); extern char *optarg;extern int optind, Opterr, optopt;getopt () the global variables that are set include: optarg--pointer to the current option parameter (if any). optind--the index of the next argv pointer when Getopt () is called again. optopt--last unknown option. 3. Supplementary description of the meaning of the specified content in optstring (e.g. getopt (argc, argv, "Ab:c:de::"); ) 1. A single character that represents an option, (as in the example above ABCDE is an option) 2. A single character followed by a colon: Indicates that the option must be followed by a parameter. Parameters are immediately followed by options or separated by a space. The pointer to the parameter is assigned to Optarg. (as in the example above B:C:) 3 A single character followed by two colons, indicating that the option can be followed by a parameter, or not followed. If a parameter is followed, the parameter must be immediately followed by an option and cannot be separated by a space. The pointer to the parameter is assigned to Optarg. (as in the above example, E::, Optarg = NULL If no argument is followed) 4. Example
#include <stdio.h>#include<unistd.h>intMainintargcChar**argv) {intch; Opterr=0; while(ch = getopt (argc,argv, "A:BCDE"))! =-1) {Switch(CH) { Case' A ':
printf ("Option A: '%s ' \ n", Optarg);
Break; Case' B ':
printf ("option b:b\n");
Break; default:
printf ("Other option:%c\n ", ch); } printf ("Optopt+%c\n ", optopt); }}
Execute $./getopt–boption B:b executes $./Getopt–cother Option:c executes $./getopt–aother option:?execute $./getopt–a12345option A: '12345’
Getopt () function