linux中getopt的函数的源代码,一个简单的GNU getopt函数的测试例子

/********************************************************

* Function: Test getopt

* Author  : Samson

* Date    : 11/30/2011

* Test platform:

*               GNU Linux version 2.6.29.4

*               gcc version 4.4.0 20090506 (Red Hat 4.4.0-4) (GCC)

* ********************************************************/

#include

#include

#include

int

main(int argc, char *argv[])

{

int flags, opt;

int nsecs, tfnd;

nsecs = 0;

tfnd = 0;

flags = 0;

while ((opt = getopt(argc, argv, "n:t:c")) != -1)

{

switch (opt)

{

case 'n':

flags = 1;

printf("case n optarg is %s \n", optarg);

break;

case 't':

nsecs = atoi(optarg);

printf("case t optarg is %s \n", optarg);

tfnd = 1;

break;

case 'c':

printf("cast c is there\n");

break;

default: /* '?' */

fprintf(stderr, "Usage: %s [-t nsecs] [-n] name\n",

argv[0]);

exit(EXIT_FAILURE);

}

}

printf("flags=%d; tfnd=%d; optind=%d\n", flags, tfnd, optind);

if (optind >= argc)

{

fprintf(stderr, "Expected argument after options\n");

exit(EXIT_FAILURE);

}

printf("name argument = %s\n", argv[optind]);

//printf parameter Reorder by getopt

for (opt = 0; opt < argc; opt++)

{

printf("argv[%d] is %s\n", opt, argv[opt]);

}

/* Other code omitted */

exit(EXIT_SUCCESS);

}

如上测试程序,当使用getopt后是会对参数列表按照getopt函数中的第三个参数规则来排序的,如测试中的"n:t:c"表示,参数应该是-n 参数 -t 参数 -c 无参数,若测试运行时输入:./a.out -c hahah -t 23 -n yygy ,而经getopt排序后的为./a.out -c -t 23 -n yygy hahah,程序测试输出为:

cast c is there

case t optarg is 23

case n optarg is yygy

flags=1; tfnd=1; optind=6

name argument = hahah

argv[0] is ./a.out

argv[1] is -c

argv[2] is -t

argv[3] is 23

argv[4] is -n

argv[5] is yygy

argv[6] is hahah0b1331709591d260c1c78e86d0c51c18.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值