getopt() function in C/C++

getopt() is used to analyze command line parameters. The parameters argc and argv represent the number and content of parameters respectively, which are the same as the command line parameters of the main() function
argc: argument count
argv: argument vector

//头文件
#include <unistd.h>

extern char *optarg;  //选项的参数指针
extern int optind,   //再调用getopt的时,从optind存储的位置处重新开始检查选项,即下一个 argv 指针的索引 
extern int opterr,  //当opterr=0时,getopt不向stderr输出错误信息。
extern int optopt;  //当命令行选项字符不包括在optstring中或者选项缺少必要的参数时,该选项存储在optopt中,getopt返回'?’、
int getopt(int argc, char * const argv[], const char *optstring);

The string optstring can have the following elements,

  1. A single character representing an option

  2. A single character followed by a colon: indicates that the option must be followed by a parameter. Parameters follow the options or are separated by spaces. The pointer to this parameter is assigned to optarg.

  3. A single character followed by two colons indicates that the option must be followed by an argument. Parameters must immediately follow the options and cannot be separated by spaces. The pointer to this parameter is assigned to optarg. (This feature is a GNU extension).

    getopt processes command line parameters starting with '-', such as optstring="ab:c::d::", the command line is getopt.exe -a -b host -ckeke -d haha.
    In
    this command line parameter, - a and -h are option elements. If '-' is removed, a, b, and c are options. host is a parameter of b, and keke is a parameter of c. But haha ​​is not a parameter of d, because they are separated by spaces. Also note that by default getopt will rearrange the order of command line parameters, so in the end all command line parameters that do not contain options are sorted last. For example,
    getopt.exe
    -a ima -b host -ckeke -d haha, The order of the final command line parameters is: -a -b host -ckeke -d ima haha
    ​​If the string in optstring starts with a '+' plus sign or the environment variable POSIXLY_CORRE is set. Then when encountering a command line parameter that does not contain options, getopt will stop and return -1

Detailed explanation of getopt() usage

おすすめ

転載: blog.csdn.net/weixin_44280688/article/details/103145802