设为首页 加入收藏

TOP

命令行参数解析精粹(一)
2014-11-23 22:57:50 来源: 作者: 【 】 浏览:3
Tags:命令 参数 解析 精粹
1. C语言
用到getopt_long这个函数, 代码如下:
/******************************************************************************
* \File
* main.c
* \Brief
*
* \Author
* Hank
* \Created date
* 2013-03-12
******************************************************************************
*/
#include
#include
#include
#include
extern char *optarg;
extern int opterr;
struct option opts[] = {
{"ip", required_argument, NULL, 'i'},
{"port", required_argument, NULL, 'p'},
{"host", required_argument, NULL, 's'},
{"out" , required_argument, NULL, 'o'},
{"help", required_argument, NULL, 'h'},
{0,0,0,0}
};
int parse_params(int argc, char** argv, char* ip, int* port, char* host, char* f);
int main(int argc, char* argv[])
{
char ip[32] = "225.1.1.31";
int port = 1234;
char host[32] = "127.0.0.1";
char filename[512] = "udp.dat";
/*Parsing command-line parameters */
parse_params(argc, argv, ip, &port, host, filename);
return 0;
}
int parse_params(int argc, char** argv,
char* ip, int* port, char* host, char* f)
{
int c, index;
opterr = 0;
while ((c = getopt_long(argc, argv, "i:p:s:o:h", opts, NULL)) != -1)
{
switch (c)
{
case 'i':
strcpy(ip, optarg);
break;
case 'p':
*port = atoi(optarg);
break;
case 's':
strcpy(host, optarg);
break;
case 'o':
strcpy(f, optarg);
break;
case 'h':
default:
printf("Usage: \n");
printf("-i ip : set udp's ip address\n");
printf("-p port : set udp's port\n");
printf("-s host : set local addresss\n");
printf("-o file : set output filename\n");
printf("-h : print help information\n");
return 1;
}
}
/* show banner */
printf("ip : %s \nport : %d \nhost : %s \nfile : %s\n",
ip, *port, host, f);
for (index = optind; index < argc; index++)
printf("Non-option argument %s\n", argv[index]);
return 0;
}
2. Perl语言版
使用Getopt::Long模块:
http://search.cpan.org/~jv/Getopt-Long-2.39/lib/Getopt/Long.pm
代码如下:
#!/usr/bin/perl
##############################################################################
# \File
# parseing_args.pl
# \Brief
#
# \Author
# Hank
# \Created date
# 2013-03-14
##############################################################################
use Getopt::Long;
my ($params, $key, $verbose, $help);
my $argc = $#ARGV; # 输入参数的个数
my $result = GetOptions("params|p=s" => \$params,
"key|k=i" => \$key,
"verbose" => \$verbose,
"help" => \$help);
if($help == 1 || $argc == -1)
{
print "Usage:\n";
print "./parsing_args.pl --params=\"...\" --key=1234 --verbose\n";
exit -1;
首页 上一页 1 2 下一页 尾页 1/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇c语言之不再害怕sizeof(struct) 下一篇杭电2008

评论

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