I am getting command line arguments from the user.
I then do switch cases for the commands, for example:
case 'f':
*file_name = optarg;
break;
I am unsure if I need to malloc for the pointer since I don't fully understand optarg.
This is how file_name is declared:
char **file_name;
Should I do
int length = strlen(optarg); // This gives a warning about types when compiling.
Then malloc for the string length + 1?
How should the malloc be done for this kind of problem? Remember the user is typing in the file_name into **argv.
EDIT: This is how I am calling this function and still getting segmentation fault.
int main(int argc, char **argv)
{
char **file_name;
parser(argc, argvm file_name);
}
void parser(int argc, char **argv, char **file_name)
{
// Switch cases.
}
'optarg' is just a pointer to an element in argv[]. So, it's safe to not allocate memory and copy the value which 'optarg' points to.
Suppose your programm is called with the following arguments:
myapp -a "hello" -b "world"
and your code is:
#include <stdio.h>
#include <getopt.h>
void parse_options(int argc, char* argv[], char ** first_arg, char ** second_arg)
{
const char* opt_string = "a:b:";
int opt = -1;
opt = getopt(argc, argv, opt_string);
while (opt != -1) {
switch(opt) {
case 'a':
*first_arg = optarg; /* points to argv[2]="hello" */
break;
case 'b':
*second_arg = optarg; /* points to argv[4]="world" */
break;
default:
break;
}
opt = getopt(argc, argv, opt_string);
}
}
int main(int argc, char* argv[])
{
char* first = 0;
char* second = 0;
parse_options(argc, argv, &first, &second);
printf("first=%s, second=%s\n", first, second);
return 0;
}
My output:
freebsd% gcc -Wall main.c
freebsd% ./a.out -a hello -b world
first=hello, second=world
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With