getopt

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

1.getopt() 用来解析命令行参数。程序启动时,argc,argv两个参数传递给运行程序,argv里的参数项以'-'(或'--')开始。循环调用getopt(),将会返回每一个参数项。

2.optind
指定argv中被处理的参数索引,初始化为1.


3.如果getopt()找到一个参数字符,返回字符,并更新optind变量和nextchar 静态变量,这样下次调用getopt()可以继续搜寻剩下的参数项。

4.如果没有找到参数项字符,getopt()返回-1.此时optind指向argv第一个元素,并不是真正的参数项。

5.optstring指定合法的选项字符。
  1)单个字符,表示选项,例如"-d"。
  2)单个字符后接一个冒号:表示该选项后必须跟一个参数。参数紧跟在选项后或者以空格隔开。该参数的指针赋给optarg,例如“-d12”或者“-d 12”。
  3单个字符后跟两个冒号,表示该选项后必须跟一个参数。参数必须紧跟在选项后不能以空格隔开。该参数的指针赋给optarg。(这个特性是GNU的扩张),譬如 ”-d12“。

6.getopt()解析到无法识别的选项,将会输出错误信息到终端,返回‘?’。




manual:http://man7.org/linux/man-pages/man3/getopt.3.html

#include "stdio.h"
#include <unistd.h>

void usage()
{
    printf("use: ./probe -i 232 -t 300 -u \"http://www.baidu.com\" -s 1 -p1\n");
    printf("\t -i _probe_id \n");
    printf("\t -t _probe_time(time:s) \n");
    printf("\t -u _probe_url\n");
    printf("\t -p _probe_type(HLS live:1 vod:2)\n");
    printf("\t -s _probe_strategy(MediaRate high:1 low:2 dynamic:3)\n");
    printf("\t -h help \n");
}

int main(int argc, char *argv[])
{
    int opt;

    while((opt = getopt(argc, argv, "?hvt:u:i:s:p::" )) != -1)
    {
        switch(opt)
        {
        case 'v':
            printf("probe-v0.0.1\n");
            exit(0);
          break;    
        case 'h':
            usage();
            exit(0);
            break;
        case 't':
            printf("_probe_time = %d\n", atoi(optarg));
            break;
        case 'i':
            printf("_probe_id = %d\n", atoi(optarg));
            break;
        case 'u':
            printf("_probe_url = %s\n", optarg);
            break;
        case 's':
            printf("_probe_strategy = %d \n", atoi(optarg));
            break;
        case 'p':
            printf("_probe_type = %d\n", atoi(optarg));        
            break;
        default:
            usage();
            exit(0);
        }
    }

    return 0;
}

Test:

[root@localhost test]# ./opt -i 232 -t 1 -u "http://www.baidu.com"  -s -p1
_probe_id = 232
_probe_time = 1
_probe_url = http://www.baidu.com
_probe_strategy = 0 
[root@localhost test]# ./opt -v
probe-v0.0.1
[root@localhost test]# ./opt -d
./opt: invalid option -- d
use: ./probe -i 232 -t 300 -u "http://www.baidu.com" -s 1 -p1
     -i _probe_id 
     -t _probe_time(time:s) 
     -u _probe_url
     -p _probe_type(HLS live:1 vod:2)
     -s _probe_strategy(MediaRate high:1 low:2 dynamic:3)
     -h help 
[root@localhost test]# 

 

posted on 2014-09-24 17:25  偏爱省略号  阅读(535)  评论(0编辑  收藏  举报

导航