getopt函数
函数原型:
#include <unistd.h>
int getopt( int argc, char* const argv[], const char* optstring);
extern char *optarg;
extern int optind, opterr, optopt;
参数 argc,argv 和main的相同
参数 optstring 记录option选项
返回值:成功获得option,返回获得的选项;否则,返回-1.
如果获得一个未定义的option,返回'?',并把 optopt设置成实际获得的option
如果发现缺少参数时,若果opstring以‘:’,开头返回‘:’,否则,返回‘?’
如果option后跟 colon ,表示有参数,参数读入optarg中
If the first character of optstring is '+' or the environment variable
POSIXLY_CORRECT is set, then option processing stops as soon as a non-option argument is encountered。
If the first character of optstring is '-', then each non-option argv-element is handled as if it were the argument of an option with
character code 1. 。
样例代码
#include <stdio.h>
#include <unistd.h>
#include <iostream>
using namespace std;
/*
just for the use of getopt
-a print "no argument is ok"
-b invarable print "argument is ok"
*/
const char opstring[]="ab:";
int main(int argc,char* argv[])
{
char opt;
while( -1 != ( opt = getopt( argc, argv , opstring ) ) )
{
switch( opt )
{
case 'a':
printf("no argument is ok.\n");
break;
case 'b':
printf("argument is ok:%s\n",optarg);
break;
case '?':
printf("error option.\n");
break;
default :
break;
}
}
return 0;
}