#include <unistd.h>
int getopt(int argc, char * const argv[], const char *optstring);
extern char *optarg;
extern int optind, opterr, optopt;
getopt函数的参数:
- 参数argc和argv:通常是从main的参数直接传递而来,argc是参数的数量,argv是一个常量字符串数组的地址。
- 参数optstring:一个包含正确选项字符的字符串,如果一个字符后面有冒号,那么这个选项在传递参数时就需要跟着一个参数。
外部变量:
- char *optarg:如果有参数,则包含当前选项参数字符串
- int optind:argv的当前索引值。当getopt函数在while循环中使用时,剩下的字符串为操作数,下标从optind到argc-1。
- int opterr:这个变量非零时,getopt()函数为“无效选项”和“缺少参数选项,并输出其错误信息。
- int optopt:当发现无效选项字符之时,getopt()函数或返回 \’ ? \’ 字符,或返回字符 \’ : \’ ,并且optopt包含了所发现的无效选项字符。