getopt: linux 下c/c++命令行参数解析

getopt

#include <unistd.h>

int getopt(int argc, char * const argv[],
           const char *optstring);

extern char *optarg;
extern int optind, opterr, optopt;

#include <getopt.h>

int getopt_long(int argc, char * const argv[],
           const char *optstring,
           const struct option *longopts, int *longindex);

int getopt_long_only(int argc, char * const argv[],
           const char *optstring,
           const struct option *longopts, int *longindex);

getopt的第一二个参数是main的两个参数,以单横岗-开头的是可选参数,getopt被多次调用时,会依次返回各个单斜杠参数。如果没有选项参数后,getopt返回-1,此时optind指向argv中的普通的非选项参数optsring给出了合法的参数串,如果某参数后面跟着一个冒号:,则该参数需要一个参数值(该值会被存到optarg中);两个冒号::表示该参数的参数值是可选的,指定时需要紧跟该参数,如-aarg,此时参数值也被存入optarg,未指定时optarg被设置为0;另外有一个GUN扩展参数:

This is a GNU extension. If optstring contains W followed by a semicolon, then -W foo is treated as the long option –foo. (The -W option is reserved by POSIX.2 for implementation extensions.)
如果getopt识别参数出错,那么返回值是’?’,参数代号被存入optopt,并将出错信息打印到stderr(如果不想将出错信息打印到stderr,则需要将特殊变量opterr设置为0)(特例情况下,会返回:,表示需要参数值缺失,其他一样).

几个特殊变量如下:
- optind: argv中下一个要被处理的元素的index,初始化为1,可以通过设置optind为1来重置扫描解析。
- opterr:设置是否将出错信息打印到stderr,设置为0则不打印,默认打印
- optopt:出错时出错的参数项被存入optopt
- optarg:正确解析时,参数值串被存入optarg

猜你喜欢

转载自blog.csdn.net/u013319359/article/details/81429991