getopt用法

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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值