command line parser

Mark J. Christophel mjc at rm1.UUCP
Tue Feb 6 08:05:23 AEST 1990


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?  i'm currently
> using one i came up with, however, i'm wondering if there might be a better
> solution.  this parser must be:
> 
> 	1)  straightford, i.e. easy to understand as well as easy to add to,
> 
> 	2)  command line arguments may be optional or required,
> 
> 	3)  program must recognize when an incorrect invocation of the program
> 	    has been made.
> 
> what i'm thinking of is an example like:
> 
> 	cluster -S /duke/data/events/ -l /duke/data/events/LOGS -m 2.5
> 
> where directories, numbers, whatever appear after the '-' argument, or not.

Try using getopt().

main (argc, argv)
int	argc;
char 	*argv[];
{
	int c;
	extern char *optarg;

	/* Third argument to getopt() is option string.  The ':'
	 * tells getopt() that the preceding option has an argument.
	 * So, 'S', 'l', and 'm' have arguments following them on the
	 * command line.  'a', and 'b' would not.
	 */
	while ((c = getopt(argc, argv, "S:l:m:ab")) != EOF)
	    switch (c)
	    {
		case 'S':
		    Sdir = optarg;	/* like your strcpy() */
					/* no need to in/decrement
					 * argc, argv.  getopt() does this.
					 */
		     .			/* rest of processing */
		     .
		     .
		    break;
		
		case 'l':
		    ldir = optarg;
		     .
		     .
		     .
		    break;

		case 'm':
		    mflag = atof(optarg);
		     .
		     .
		     .
		    break;

		case 'a':
		    aflag = TRUE;
		     .
		     .
		     .
		    break;

		case 'b':
		    bflag = TRUE;
		     .
		     .
		     .
		    break;

		case '?':
		default:
		    /* Invalid option, error message displayed by
		     * getopt() I believe.
		     */
		    break;
	    }
	/* rest of processing */
}

> 
> i would apreciate any responses via the newsgroup or email to me.  
> thanks in advance.

--

Mark J. Christophel		!rm1!mjc	       (305) 846-6873
Racal-Milgo, P.O. Box 407044, MS E112, Ft. Lauderdale, FL  33340-7044
-- 
Mark J. Christophel		   novavax!rm1!mjc		  (305) 846-6873
[M. Christophel, Racal-Milgo, MS E112, Box 407044, Ft Lauderdale, FL 33340-7044]



More information about the Comp.lang.c mailing list