getopt_long() function with custom argc and argv

1.7k views Asked by At

I am having trouble using getopt_long() function with custom argc and argv.

I receive my arguments in a string instead of the real command line args. Then a new_argc and new_argv was built from this string to be used with getopt_long(). But getopt_long() fails on the first call itself. returns EOF and optarg = NULL.

string is "-c 10.30.99.41" 
new_argc = 3
new_argv[0]=>./prog_name
new_argv[1]=>-c
new_argv[2]=>10.30.99.41

getopt_long works OK for me if I pass command line args. So my short and long options are correct. But if I pass the new_argc and new_argv it fails.

I am sure my short and long options are right and the argv is NULL terminated. I apologize I cant post more code here.

I doubt if getopt_long can be used with a custom argc and argv. I suspect it works only with a real argc and argv because it must be referencing some other code in libc related to argc,argv. Any comments?

option = getopt_long( new_argc, new_argv, short_options, long_options, NULL );
1

There are 1 answers

1
nos On BEST ANSWER

EDIT:

"The variable optind is the index of the next element to be processed in argv. The system initializes this value to 1. The caller can reset it to 1 to restart scanning of the same argv, or when scanning a new argument vector."

So, yes. You can use getopt_long to scan the arguments or another argument list again. However, if someone has called getopt_long previously, you have to set the global optind variable to back to 1.

Remember that the argv in main() is NULL terminated and argc long, that is; argv[argc] == NULL. So you likely have to make sure the last element in your own new_argv is a NULL pointer.

(Note, please show all the relevant code when posting, it's hard to guess what the error is, e.g. showing what short_options, long_option is, how you actually build your new_argv, variable declarations etc.)