command line parser

Peter da Silva peter at ficc.uu.net
Wed Feb 7 01:11:19 AEST 1990


In article <232 at rm1.UUCP> mjc at rm1.UUCP (Mark J. Christophel) writes:
> In article <2048 at lamont.ldgo.columbia.edu>, boaz at lamont.ldgo.columbia.edu (richard boaz) writes:
> > does anyone happen to have a nice clean command line parser in C?

> > 	cluster -S /duke/data/events/ -l /duke/data/events/LOGS -m 2.5

> Try using getopt().

No, try using parseargs() by Eric Allman. I've made some enhancements to it,
and recently posted diffs to alt.sources. The original will be coming out in
comp.sources.unix if Rich $alz ever wakes up, or you can ftp it from:

ucbarpa.berkeley.edu [128.32.130.11] pub/c_advisor/parseargs.shar

I'm thinking I should maybe post my complete code to alt.sources.

#include <parseargs.h>

char *Log = DEFAULTLOG;
char *Sdir = DEFAULTDIR;
float mflag = 0.0;
int aflag = 0, bflag = 0;

ARGDESC	Args[] =
{
	'S',	ARGOPT,		argStr,		__ &Sdir,	"Directory",
	'l',	ARGOPT,		argStr,		__ &Sdir,	"Logfile",
	'm',	ARGOPT,		argFloat,	__ &mflag,	"MFlag",
	'a',	ARGOPT,		argBool,	__ &aflag,	"AFlag",
	'b',	ARGOPT,		argBool,	__ &bflag,	"BFlag",
	ENDOFARGS
};

main(argc, argv)
	int argc;
	char **argv;
{
	int newargc;

	newargc = parseargs(argv, Args, "File");

	/* Now argv just contains actual file name arguments. */
}

Isn't that much simpler than getopt? And, it will automatically generate
the following usage message:

Usage: program [-S <Directory>] [-l <Logfile>] [-m <MFlag>] [-a] [-b] \
	[<File>]...

The exact same code, on the Amiga (with the Amiga version of parseargs I'm
working on) will implement Amiga syntax:

Usage: program [DIRECTORY <Directory>] [LOGFILE <Logfile>] [MFLAG <Mflag>] +
	[AFLAG] [BFLAG] [<File>]...

Similarly, VMS users would be able to use, with a slightly modified library:

Usage: program [/Directory=<Directory>] [/Logfile=<Logfile>] [/MFlag=<MFlag>] -
	[/AFlag] [/BFlag] [<File>]...

And in all of the above you get argument type checking, meaningful error
messages, and so on.

I'm much impressed with Eric's concept, and with minimal tweaking this becomes
the biggest advance in command line parsing since argv[argc] was -1.
-- 
 _--_|\  Peter da Silva. +1 713 274 5180. <peter at ficc.uu.net>.
/      \
\_.--._/ Xenix Support -- it's not just a job, it's an adventure!
      v  "Have you hugged your wolf today?" `-_-'



More information about the Comp.lang.c mailing list