Saturday, 6 December 2008

Basics of gnu.getop

A Java port of GNU getopt based on C getopt() functions in glibc. Getopt partitions the inputs to the command-line program into optional and non-optional inputs.

import gnu.getopt.Getopt;

Getopt g = new Getopt("porridge", (String[]) args, "a:b:c:");
g.setOpterr(false); // we'll do our own error handling

while((c=getopt())!=-1) {
switch(c) {
case 'a': _alpha = g.getOptarg(); break;
case 'b': _beta = g.getOptarg(); break;
case 'c': _gamma = g.getOptarg(); break;
}

Once these options are processed, the next phase is to process non-optional arguments.
A summary of useful methods on Getopt object:

g.getopt() - returns the current option passed to the command-line
g.getOptind() - returns the NEXT index in ARGV of the next element to be scanned (non-optional argument)

No comments:

Blog Archive