Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use C++ getopt_long() if I have more than 26 options?

Tags:

c++

This is a rather hypothetical question, but let's say I have 3 long parameters that begin with the same letter.

--parse or -p
--prune or -r
--pivot or -i

Eventually I'll start running out of single letters that make sense, more over, it's hard assign something meaningful in GNU getopt_long() configuration.

{"parase", no_argument,       0, 'p'},
{"prune",  no_argument,       0, 'r'},
{"pivot",  required_argument, 0, 'i'}

What is the best practice in these situations?

like image 595
Mikhail Avatar asked Nov 17 '11 14:11

Mikhail


People also ask

Does getopt modify argv?

(The -W option is reserved by POSIX. 2 for implementation extensions.) This behavior is a GNU extension, not available with libraries before glibc 2. By default, getopt() permutes the contents of argv as it scans, so that eventually all the nonoptions are at the end.

How does getopt work in C?

The getopt() function is a builtin function in C and is used to parse command line arguments. Syntax: getopt(int argc, char *const argv[], const char *optstring) optstring is simply a list of characters, each representing a single character option.

What library is getopt in C?

getopt is a C library function used to parse command-line options of the Unix/POSIX style. It is a part of the POSIX specification, and is universal to Unix-like systems. It is also the name of a Unix program for parsing command line arguments in shell scripts.

How does getopt work?

Normally, getopt is called in a loop. When getopt returns -1 , indicating no more options are present, the loop terminates. A switch statement is used to dispatch on the return value from getopt . In typical use, each case just sets a variable that is used later in the program.


3 Answers

You don't have to use printable characters for the val member. Moreover, it's int, not char. It should just assist you with identifying the option. (meaning, you don't have to have corresponding shorty).

like image 186
Michael Krelin - hacker Avatar answered Sep 23 '22 03:09

Michael Krelin - hacker


You have a choice of uppercase, as well as lowercase, giving you 52 short options, however many programs that accept long options don't even bother assigning short options to some options, forcing the user to use the long options only, which OK.

like image 22
trojanfoe Avatar answered Sep 24 '22 03:09

trojanfoe


The digits 0-9 can be used to. Imagine a data compression program which would either accept -compression=[0-9], or just -[0-9] (I don't know if this works with getopt, though).

Also, uppercase can be used, too.

I understand that's a hypothetical question, but with so many options, the program probably does too much or needs a configuration file.

like image 28
Sebastian Mach Avatar answered Sep 24 '22 03:09

Sebastian Mach