Command-Line Argument Processing and the Argv Library
by Oliver Goldman

Listing One
int main( int argc, char **argv ) {
    int c;
    extern char *optarg;
    extern int optind;
    int aflg = 0;
    int bflg = 0;
    int errflg = 0;
    char *ofile = NULL;

    while ((c = getopt(argc, argv, "abo:")) != EOF)
        switch (c) {
          case 'a':
            if (bflg)
              errflg++;
            else
              aflg++;
            break;
          case 'b':
            if (aflg)
              errflg++;
            else
              bflg++;
            break;
          case 'o':
            ofile = optarg;
            break;
          case '?':
            errflg++;
        }
        if (errflg) {
           fprintf( stderr, "usage: cmd [-a|-b] [-o <filename>] files...\n" );
           return 2;
        }
    }
    ...
}

Listing Two
import com.charliedog.argv.*;
import java.io.PrintWriter;
import java.util.List;

public static void main( String[] argv ) {

    // Initialize arguments that may appear in the command line. By convention,
    // '-help' simply prints the command line usage and exits.
    StringArgument destination = 
       new StringArgument( "-dest", "localhost", "Destination for requests" );
    BooleanArgument help = 
       new BooleanArgument( "-help", "Describe command line args" );
    // Initialize and invoke the parser. Arguments not consumed during parse
    // are returned in case they may be subject to additional processing, etc.
    // Variable 'args' is assumed to contain String array passed to main().

    ArgumentParser parser = new ArgumentParser();
    parser.addArgument( destination );
    parser.addArgument( help );
    List extra = parser.parse( argv );

    // For this application, extra arguments will be treated as a usage error.
    if( !extra.isEmpty() || help.getValue()) {
        PrintWriter out = new PrintWriter( System.out );
        parser.printUsage( out );
        out.close();
        System.exit( 0 );
    }
    // Continue, using destination.getValue()...
}

Listing Three
public List parse( String args[] ) {
    List values = Arrays.asList( args );
    List extras = new LinkedList();
perValue: while( !values.isEmpty()) {
        // Give each Argument a shot at parsing the list in its
        // current form. Stop on the first match.

        Iterator i = arguments.iterator();
        while( i.hasNext()) {
            Argument arg = (Argument)( i.next());
            int numArgsConsumed = arg.parse( values );
            if( numArgsConsumed > 0 ) {
                values = values.subList( numArgsConsumed, values.size());
                continue perValue;
            }
        }
        // If no matches were found, move the first value to the extras
        // list and try again. Don't use values.remove( 0 ) here because
        // it is an optional method.
        extras.add( values.get( 0 ));
        values = values.subList( 1, values.size());
    }
    return extras;
}





2


