前一阵子写了一个生成原始实验数据的程序,为了方便使用,我想到了以前看过的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;
}