getopt_long的使用

在项目学习的过程中,看到代码中有用到getopt_long()函数,网上查了一下资料,发现这个函数还是挺有用的。于是,自己写了一段代码,来加强理解。

代码如下:

/*
 * name: my_getopt_long.c
 * coder:[email protected]
 * time:02.06.2012
 */
#include <stdio.h>
#include <getopt.h>
#include <assert.h>

char short_options[] = "hw?";

int printf_help()
{
	printf("        [-h|--hello <status/number]\n");
	printf("        [-w|--world <status/number]\n");
	return 0;
}

struct option long_options[] = 
{
	{"hello ", 0, NULL, "h"},
	{"world", 0, NULL, "w"},
	{0, 0, 0, 0},
};

int main(int argc, char **argv)
{
	assert((argc != NULL) && (argv != NULL));
	int i = 0,opt = 0,err_flag = 0, ret = -1, action[128] ={0};

	while ((opt = getopt_long(argc, argv, short_options, long_options, NULL)) != -1) 
	{
		switch(opt) 
		{
			case 'h':
				printf("hello \n");
				break;
			case 'w':
				printf("world\n");
				break;
			case '?':
				err_flag = 1;
				break;
		}
		i++;
	}
	if (optind > argc || err_flag == 1) 
	{
		printf("optind = %d\n",optind);
		printf("argc = %d\n",argc);
		printf("Error : Wrong input!\n");
		printf_help();
		_exit(1);
	}
	return 0;
}


你可能感兴趣的:(struct,null,input,action)