设为首页 加入收藏

TOP

一个简单的GNU getopt函数的测试例子
2014-11-24 13:51:41 来源: 作者: 【 】 浏览:1
Tags:一个 简单 GNU getopt 函数 测试 例子

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


#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 hahah


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇高通MSM8255 GPS 调试分析 下一篇Android 下载文件(支持多任务,支..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: