getopt让你的程序更易用

前一阵子写了一个生成原始实验数据的程序,为了方便使用,我想到了以前看过的getopt,这次就只贴代码,以后自己找出来看。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>/*getopt()*/
//#include <getopt.h>
#include <string.h>
#include <time.h>

//#define RAND_MAX 2147483647
static void usage(char * argv0){
	char *help=
		"Usage: %s [switches] -x filename -f from -t to -n num -d dim \n"
		"	-x filename	:filename of output file\n"
		"	-f from 	:range from\n"
		"	-t to		:range to\n"
		"	-n num		:total number of object\n"
		"	-d dim		:dim of object\n"		
		"	-? help		:get help~~\n";
	printf("%s",help);
	//fprintf(stderr,help,argv0);
	exit(-1);
}

int main(int argc,char **argv)
{
	int i,j=0;
	int opt=0;
	int digit_num=0;
	int from=0;
	int to=0;
	int num=0;
	int dim;
//	char filename[1024];
	const	char * filename;
	float tmp=0.0;
	float * tmp_object=NULL;
	FILE * fp=NULL;
	printf("my pid = %d \n",getpid());
	while((opt=getopt(argc,argv,"x:f:t:n:d:?"))!=EOF){
	  	switch(opt){
			case 'x': 
				  filename=optarg;
				  printf("case x=%s\n",filename);
				  break;			
			case 'f': from=atoi(optarg);
				  printf("case f =%s\n",optarg);
				  break;
			case 't': to=atoi(optarg);
				  printf("case t =%s\n",optarg);
				  break;
			case 'n': num=atoi(optarg);
				  printf("case n=%s\n",optarg);
				  break;
			case 'd': dim=atoi(optarg);
				  printf("case d=%s\n",optarg);
				  break;	
			case '?': usage(NULL);
			default:  //usage(NULL);
				  break;
		}
	}
//usage(NULL);
	if(filename == 0|from==0||to==0||num==0||dim==0) usage(NULL);
          printf("starting!\n"); 
 	/*---------------------genarate random digit------------------------*/
	srand((int)time(0));
	tmp=0.0;
	tmp_object=malloc(dim * sizeof(float));
	fp=fopen(filename,"w");
	for(i=0;i<num;i++)
	{
		fprintf(fp,"%d ",i+1);
		for(j=0;j<dim;j++)
		{
			tmp_object[j]=(float)(rand()%(to-from+1))+from;
			tmp_object[j]+=rand()/(float)RAND_MAX;
			fprintf(fp,"%6f ",tmp_object[j]);			
		}
		fprintf(fp,"\n");		
	}
	fclose(fp);
	free(tmp_object);
	return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值