Linux in getopt detailed
The Getopt function is used to parse the command-line arguments, with the argument "-'" or '--' as the option parameter, and the option parameter to remove '-' or '--' to the left of the option character . if the getopt function is called repeatedly, it returns the option character in each option element, in turn.
The following header files are required to use getopt:
#include <unistd.h>
#include <getopt.h>
There are several global variables related to the GETOPT function parsing parameters:
optind: int, indicating the next parameter position to parse, initially at 1.
optarg: char *, you must take the parameters of the option element of the parameter, such as the-nxzz above, Optarg points to the "Xzz" string.
opterr: type int, set to 0 will not print error messages.
The function prototypes are:
int getopt (int argc, char * const argv[], const char *optstring);
Parameter description:
The first two parameters are the same as the main function parameter, ARGC save the number of parameters, argv[] Save the parameter array, the third parameter optstring is our own definition of the option character string , such as "ABC", indicating that the command has three options parameter-A,-B,- C, after the option character, if there is a colon stating that the option element must have an argument, and the argument is saved in Optarg, such as "n:t" means that the option element n is followed by an argument, and the option element T is followed by a parameter, such as-n xxz-t or-nxzz T, There are two colons that indicate that the option can be optional, but optional parameters are not present in Optarg
return value:
If the parameter that is currently being processed is an option parameter , and the option character is in the optstring string, which is the option you define, the option character is returned, and if the option character is not defined by you, return the character '? ', and update the global variable Optind, pointing to the next parameter in the ARGC array . If the parameter currently being processed is not an option parameter, Optind offsets the next argument until the first option element is found, and then presses the action described previously, and returns 1 if the option element is not found, stating the end of the resolution.
Linux in getopt detailed