I am trying to use getopt to parse command line options passed by the user of the program. I am specifically struggling with how to save the "option arguments" that are passed with flag, for example like below.
./main -r 213
I am trying to set it up in a way where argument order doesn't matter, and several of my options could pass strings as their argument that I would like to save to a variable. I.e., like below.
./main -o bmp
I have been looking at several resources, but am having trouble even getting the basic ones to print out. For example the code below:
int r, g, b, c;
char t[3];
while ((c = getopt (argc, argv, "abc:")) != -1)
switch (c)
{
case 'r':
printf("Option r has option %s\n", optarg);
break;
case 'g':
printf("Option g has option %s\n", optarg);
break;
case 'b':
printf("Option b has option %s\n", optarg);
break;
break;
case 't':
printf("Option t has option %s\n", optarg);
break;
}
When given this command line argument:
./main -r 123 -g 89 -b -76
Produces this:
./main: invalid option -- 'r'
./main: invalid option -- 'g'
Option b has option (null)
./main: invalid option -- '7'
./main: invalid option -- '6'
Like I mentioned what I actually want to do is store these option arguments off, but I was trying this to understand how they're structured.
getopt()that it should look for the options-aand-bwithout arguments and-cwith one. But that's not how you invoke your program...abc:and then you call it with the arguments -r, -g- and -b. Only argumentctakes an value.