利用getopt_long()为程序传入参数

man getopt_long,得到其声明如下:

int getopt_long(int argc, char * const argv[],const char *optstring, const struct option *longopts,int *longindex);
函数中的argc和argv通常直接从main()的两个参数传递而来。optsting是选项参数组成的字符串:
字符串optstring可以下列元素:
1.单个字符,表示选项,
2.单个字符后接一个冒号:表示该选项后必须跟一个参数。参数紧跟在选项后或者以空格隔开。该参数的指针赋给optarg。
3 单个字符后跟两个冒号,表示该选项后可以有参数也可以没有参数。如果有参数,参数必须紧跟在选项后不能以空格隔开。该参数的指针赋给optarg。(这个特性是GNU的扩张)。


参数longopts,其实是一个结构的实例:

struct option {
	const char *name; //name表示的是长参数名
	int has_arg; //has_arg有3个值,no_argument(或者是0),表示该参数后面不跟参数值, required_argument(或者是1),表示该参数后面一定要跟个参数值, optional_argument(或者是2),表示该参数后面可以跟,也可以不跟参数值
	int *flag;//用来决定,getopt_long()的返回值到底是什么。如果flag是null,则函数会返回与该项option匹配的val值
	int val; //和flag联合决定返回值
}

小例子:

#include <stdio.h>  
#include <getopt.h>  
#include <stdlib.h>  
  
/*单个字符,表示选项,单个字符后接一个冒号:表示该选项后必须跟一个参数。 
参数紧跟在选项后或者以空格隔开。该参数的指针赋给optarg。 
optarg不需要定义,在getopt.h中已经有定义)*/  
char* const short_options = "hnd:g:";  
  
struct option long_options[] = {  
    { "help", 0, NULL, 'h'},  
    { "no", 0, NULL, 'n' },  
    { "long", 1, NULL, 'd' },  
	{ "long", 1, NULL, 'g'},
    { 0, 0, 0, 0},  
};  

void print_usage(FILE *stream)  
{  
    fprintf(stream, "Usage: option [ dev... ] \n");  
    fprintf(stream,  
            "\t-h  --help     Display this usage information.\n"  
            "\t-n  --no_argument    No argument is running\n" 
			"\t-g  --传递ip\n"
            "\t-d  --DEBUG\n");  
    exit(0);  
}  

int main(int argc, char *argv[])  
{  
    int c = 0;  
    char *dbgbuf = NULL;  
	char *ipbuf = NULL;
	
    if(argc < 2){  
        print_usage(stdout);  
    }  
    while((c = getopt_long(argc, argv, short_options, long_options, NULL)) != -1)  
    {  
        switch (c)  
        {  
			case 'g':
				ipbuf = optarg;
				printf("ip=%s\n", ipbuf);
				break;
            case 'h':  
                print_usage(stdout);  
                break;  
            case 'n':  
                printf("no_argument\n");  
                break;  
            case 'd':  
                dbgbuf = optarg;  
                printf("debug is %s!\n", dbgbuf);  
				while(1)
				{
					if(strcmp(dbgbuf, "GPSON")==0)
					printf("gps printf is runing\n");
					sleep(1);
				}
                break; 
			default:
				break;
        }  
    }  
    return 0;  
}  


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值