getopt函数的用法

Linux提供了一个解析命令行参数的函数。

#include <unistd.h>

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

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

使用这个函数,我们可以这样运行命令

./a.out -n -t 100

n后面不需要参数,t需要一个数值作为参数。

代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#define ERR_EXIT(m) \
    do { \
        perror(m);\
        exit(EXIT_FAILURE);\
    }while(0)


int main(int argc, char *argv[])
{
    int opt;
    while(1)
    {
        opt = getopt(argc, argv, "nt:");
        if(opt == '?')
            exit(EXIT_FAILURE);
        if(opt == -1)
            break;

        switch(opt)
        {
            case 'n':
                printf("AAAAAAAA\n");
                break;
            case 't':
                printf("BBBBBBBB\n");
                int n = atoi(optarg);
                printf("n = %d\n", n);
        }
    }
    return 0;
}

当输入非法参数时,getopt返回’?’,当解析完毕时,返回-1.

如果需要参数,那么使用optarg获取,这是一个全局变量。

注意getopt的第三个参数”nt:”,说明可用的参数有n和t,t后面有一个冒号,说明t需要额外的参数。

运行结果如下:

5:30:22 wing@ubuntu msg ./getopt_test -n
AAAAAAAA
5:30:26 wing@ubuntu msg ./getopt_test -t 
./getopt_test: option requires an argument -- 't'
5:30:31 wing@ubuntu msg ./getopt_test -t 100                                           1 ↵
BBBBBBBB
n = 100

转载于:https://www.cnblogs.com/inevermore/p/4121981.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值