getopt_long()函数
时间:2009-04-13 来源:nanqihao
getopt 函数
函数定义:
extern char *optarg;
int getopt_long(int argc, char * const argv[],
int getopt_long_only(int argc, char * const argv[],
getopt_long()的头两参数,argc和argv分别是传递给main()的参数的个数和参数数组(和main()的argc和argv是一个概念)。 getopt_long()中,optstring是一个字符串,表示可以接受的参数。例如,"a:b:cd",表示可以接受的参数是a,b,c,d,其中,a和b参数后面 跟有更多的参数值。(例如:-a host --b name)
getopt_long()中,参数longopts,其实是一个结构的实例: 给个例子:
struct option long_options[] = { 现在,如果命令行的参数是-a 123,那么调用getopt_long()将返回字符'a',并且将字符串123由optarg返回(注意注意!字符串123由optarg带
回!optarg不需要定义,在getopt.h中已经有定义) 最后,当getopt_long()将命令行所有参数全部解析完成后,返回-1。 看来,我说的有点混乱,那么,看个例子,我相信,代码最能说明问题:
#include
int main( int argc, char **argv )
struct option long_options[] = {
编译后,假设生成a.out,可以试验一下。 |