I want to rewrite a program starting with main(){} so that I can use it as a function. Normally the program expects an input file an output file and optionally up to 6 arguments. I pass them within the command line with:
programname --opt1 --op2 --op3 <input file> output file
The different arguments in the program are then read by getopt_long (int argc, char *const *argv, const char *shortopts, const struct option *longopts, int *indexptr)
.
When I want to create a function out of this I have to swith the name main()
to some other, lets say programname()
, besides I have to directly pass the arguments, so out of
main(int argc, char **argv){}
it becomes e.g.:
main(int opt1, int opt2, int opt3, FILE *infile, FILE *outfile){}
My question is: how can I manage the optionality of the number of input arguments? With getopt_long
I can manage this with using --opt1
instead of -opt1
, but getopt_long
can just be used within a main function, or?
Can I somehow create a function that has no specified number of inputs?
Thanks for your help!
EDIT: Now I try to read argv from user with scanf()
A small example, you can try e.g: first input: --dd=2 second input: ok
#include <getopt.h>
void main(){
char **options = (char**) malloc(6*sizeof(char*));
int i;
for(i=0;i<6;i++){
options[i] = (char*) malloc(100*sizeof(char));
}
int argc=1;
printf("%s\n", "insert your options. e.g.: [--ngf=20]");
printf("%s\n", "if finished press [ok]");
scanf("%s",options[argc]);
while (strcmp(options[argc],"ok")!=0){
argc++;
scanf("%s",options[argc]);
}
char **argv = (char**) malloc(argc*sizeof(char*));
for(i=0;i<argc;i++){
argv[i] = (char*) malloc(100*sizeof(char));
}
for(i=0;i<argc;i++){
argv[i] = options[i];
}
/* Process Arguments */
optind = 1;
double aa,bb,cc;
int c, dd;
int option_index = 0;
static struct option long_options[] = {
{"aa", 1, 0, 1},
{"bb", 1, 0, 2},
{"cc", 1, 0, 3},
{"dd", 1, 0, 4},
{0, 0, 0, 0}
};
while ((c = getopt_long(argc,argv,"hgt",
long_options, &option_index)) != -1) {
switch (c) {
case 1: if (sscanf(optarg,"%lg",&aa) != 1)
fun_Stop("incorrect format");
break;
case 2: if (sscanf(optarg,"%lg",&bb) != 1)
fun_Stop("incorrect format ");
break;
case 3: if (sscanf(optarg,"%lg",&cc) != 1)
fun_Stop("incorrect format");
break;
case 4: if (sscanf(optarg,"%i",&dd) != 1)
fun_Stop("incorrect format");
break;
default :
break;
}
}
}