[Courses] [C] getopt() and getopt_long()

Akkana akkana at shallowsky.com
Sat Aug 10 10:21:27 EST 2002

Anand R writes:
> 	Could we have a discussion on using parsing command line arguments.
> Typically, we have programs today, that use getopt() and getopt_long() for
> parsing command line arguments (they have made life a lot more easier for
> us). A small discussion on best practices, cute hacks and
> guidelines/pitfalls/best practices would be really useful and would greatly
> benefit newbies. 

I usually "cheat" with getopt -- I can never remember the syntax (and
it seems to vary between versions, and of course between languages),
so I go find a program that uses it, grab a few lines and stuff them
into my program, then edit appropriately.

Lately I've been poking around the argument parsing of some of the
pilot-link programs (pilot-link.org, used for syncing Palm Pilots)
since the latest version has reworked a lot of the command arguments
to be much more consistent, but a few programs still need cleaning up.
The getopt use in these programs generally looks like this (from
pilot-xfer.c, the main program in pilot-link) and it's pretty easy
to read this code or adapt it to other programs:

struct option options[] = {
	{"help",        no_argument,       NULL, 'h'},
	{"version",     no_argument,       NULL, 'v'},
	{"port",        required_argument, NULL, 'p'},
[ ... ]
	{NULL,          0,                 NULL, 0}

static const char *optstring = "-hvp:b:u:s:Sr:i:m:f:d:e:PlLa:x:FOIqc";

[ ... ]

int main(int argc, char *argv[])
[ ... ]
	while ((c = getopt_long(argc, argv, optstring, options, NULL)) != -1) {
		switch (c) {

		/* This means a field is unknown, could be multiple arg * */
		case 1:
			if (last_c=='i') {
			/* else { Unknown param, let it go by quietly } * */
		case 'h':
			return 0;
		case 'v':
			return 0;
		case 'p':
			port = optarg;
[ ... ]

and so forth.  It's mostly pretty straightforward (except the "case 1"),
but for some reason I have a hard time remembering the syntax so I find
it much easier to stea^H^H^H^Hcopy.

I do use the _long version, both in C and perl, because it's not
that much harder to use, and it seems more civilized to support both
long and short format arguments.

The "case 1" there looks lke a nifty trick to handle multiple arguments
(which getopt otherwise doesn't deal with gracefully.  I never noticed
it before, but I'm going to use it myself now that I know about it. :-)


More information about the Courses mailing list