I have a program which takes in multiple command line arguments so I am using getopt. One of my arguments takes in a string as a parameter. Is there anyway to obtain that string through the getopt function or would I have to obtain it through the argv[] array? Also can getopt read args like -file
? All the arguments I have seen till now have only one character such as -a
EDIT
From the below answers I have written a program to use getopt_long(), but the switch statement only recognizes the argument when I use the character argument and not the long argument. I'm not sure why this happening. On passing the arguments -mf -file sample
I do not see the print statements.
EDIT
I tried entering the command arguments as --file
and then it worked. Is it not possible to do this with just -file
?
static struct option long_options[] =
{
{"mf", required_argument, NULL, 'a'},
{"md", required_argument, NULL, 'b'},
{"mn", required_argument, NULL, 'c'},
{"mw", required_argument, NULL, 'd'},
{"lf", required_argument, NULL, 'e'},
{"ld", required_argument, NULL, 'f'},
{"ln", required_argument, NULL, 'g'},
{"lw", required_argument, NULL, 'h'},
{"rf", required_argument, NULL, 'i'},
{"rd", required_argument, NULL, 'j'},
{"rn", required_argument, NULL, 'k'},
{"rw", required_argument, NULL, 'l'},
{"df", required_argument, NULL, 'm'},
{"dd", required_argument, NULL, 'n'},
{"dn", required_argument, NULL, 'o'},
{"dw", required_argument, NULL, 'p'},
{"file", required_argument, NULL, 'q'},
{NULL, 0, NULL, 0}
};
int ch=0;
while ((ch = getopt_long(argc, argv, "abcdefghijklmnopq:", long_options, NULL)) != -1)
{
// check to see if a single character or long option came through
switch (ch){
case 'a':
cout<<"title";
break;
case 'b':
break;
case 'c':
break;
case 'd':
break;
case 'e':
break;
case 'f':
break;
case 'g':
break;
case 'h':
break;
case 'i':
break;
case 'j':
break;
case 'k':
break;
case 'l':
break;
case 'm':
break;
case 'n':
break;
case 'o':
break;
case 'p':
break;
case 'q':
cout<<"file";
break;
case '?':
cout<<"wrong message"
break;
}
}
See Question&Answers more detail:
os