Linux程序设计中参数的解析

先上代码片,这是一个示例,通过函数循环读取我们的参数到optarg中,再通过一系列的格式化或者转换把相应的参数放在固定位置上。发现自己英语水平太差,所以试着写写英文的。
Let’s see the under code first, it’ss an example in which we read the opt to optarg for a loop and then through a series of formatting or conversion put them to the corresponding parameters.
代码示例(code example):

int opt;
while((opt = getopt(argc,argv,"q:w:e:m:M:i:I:p:P:t:n:s:c:")) != -1) {
    switch(opt) {
        case 'q':
            qps = atoi(optarg);
            qps = qps>0?qps:1;
            break;
        case ...:
        case ...:
    }
}

函数的原型(function declaration):

#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是一个我们要读取的参数的标注集合。
In the function’s parameter list, argc and argv are the arguments passed by main.optstring is a argument-flag set.

在optstring中,有三种格式:
1. “aoe”: 表示我们需要读取aoe这三个字符,但这三个字符后是不带参数的
2. “a: o: e:”:表示我们需要读取的这三个字符后带有参数,optarg会指向相应的参数
3. “a:: o:: e::”:表示三个字符后可能带有参数,如果有的话不许用空格隔开,optarg指向相应参数

getopt()会返回获取到的参数标志,并将全局变量optarg设置为对应的值(如果是后两种格式),还可能会设置其他一些变量。如果没有可以匹配的参数,函数将返回-1。
getopt() will return the parameters flag what we get and set corresponding value to the global variable optarg. If there are no rest flag we need, the function will return -1.

各个全局变量的意义:
1. optarg: 当前获取的参数值
2. optind: argv当前的索引值
3. opterr: 非零时表示当前参数为“无效选项”和“缺少参数选项“,并输出错误信息
4. optopt:发现无效选项字符时函数返回’?’或者’:’,optopt包含了所发现的无效字符用于输出
The meaning of all the global variables:
1. optarg: the parameter value we get now
2. optind: the index of argv
3. opterr: nonzero means that the parameter is error and print the error information
4. optopt:the function return ‘?’ or ‘:’ when it face the invalid option, and optopt get the invalid option

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值