命令行参数处理

[url]http://www.ibm.com/developerworks/cn/aix/library/au-unix-getopt.html[/url]

[url]http://hi.baidu.com/harite/blog/item/2ad9aaec43f87b3d2697913d.html[/url]


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <getopt.h>
#include <string.h>

struct Student
{
int id;
char *name;
};

// optSting是选项参数组成的字符串,
// 字符后跟一个冒号,表明该选项要求有参数。
static const char *optString = "i:n:h?";

// option结构称为长选项表,其声明如下:
//struct option { // 四个域分别是
// const char *name; // --长指令
// int has_arg; // required_argument 1:带参数 no_argument 0:不带参数
// int *flag; // NULL
// int val; // -短指令
//};
// option结构数组,最后以 { NULL, no_argument, NULL, 0} 结束

static const struct option longOpts[] = {
{ "id", required_argument, NULL, 'i'},
{ "name", required_argument, NULL, 'n'},
{ "help", no_argument, NULL, 'h'},
{ NULL, no_argument, NULL, 0}
};

void Help( void )
{
puts( "Help: \n not help~" );
exit( EXIT_FAILURE );
}

int main( int argc, char *argv[] )
{
struct Student boy = {0,NULL};

int opt;
while ( (opt = getopt_long(argc,argv,optString,longOpts,NULL )) != -1 )
{
switch ( opt )
{
case 'i':
boy.id = atoi(optarg);
break;

case 'n':
boy.name = optarg;
break;

case 'h':
case '?':
Help();
break;
default: break;
}
}

printf( "id: %d\n", boy.id );
printf( "name: %s\n", boy.name );

return EXIT_SUCCESS;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值