I need to parse arguments using the getopt
function. The problem is if I have arguments before and/or after options, getopt
doesn't work. Option processing stops as soon as a nonoption argument is encountered.
For exemple : tftp ip port [-b blksize] src dest
doesn't work.
But tftp [-b blksize] ip port src dest
works well.
Apparently, I need to add +
at the beginning of optstring
to be able to mix arguments and options but it doesn't supported on Max OS X according to https://www.gnu.org/software/gnulib/manual/html_node/getopt.html
Have you a solution? Thanks.
Change what you pass getopt
in as argv
and argc
to skip over the command portion.
For example, tftp ip port [-b blksize] src dest
you'd pretend port
at argv[2]
is argv[0]
. Call getopt(argc - 2, argv + 2, optstring)
.
#include <unistd.h>
#include <stdio.h>
int main(int argc, char *argv[]){
int ch;
while( (ch = getopt(argc - 2, argv + 2, "b:")) != -1 ) {
printf("%c %s\n", ch, optarg);
}
return 0;
}
This is just an example. It's up to you to add the logic to determine if there is a command or subcommand.