getopt.c

/*
 * GETOPT -- show how getopt(3) handles options
 *
 * Matt Bishop, ECS 36A
 *
 * April 30, 2024
 *      -- original program written
 */

#include <stdio.h>
#include <unistd.h>
#include <getopt.h>

extern char *optarg;		/* argument to option */
extern int optind;		/* index to next command line argument */
extern int opterr;		/* 0 to suppress errors from getopt, non-zero otherwise */
extern int optopt;		/* erroneous option if opterr is non-zero */

/*
 * a list of options to look for
 * if letter is not followed by :, the option does not have an argument
 * if letter is followed by :, the option *must* have an argument
 * if letter is followed by ::, the option *may* have an argument
 */
char *optstring = "ae:fx::y";

/*
 * main program
 */
int main(int argc, char *argv[])
{
	int c;		/* return value of getopt */
	int i;		/* counter in a for loop */

	/*
	 * loop until you finish dealing with the options
	 */
	while((c = getopt(argc, argv, optstring)) != -1){
		switch(c){
		case 'a':		/* plain old option */
			printf("%s: got 'a' option\n", argv[0]);
			break;
		case 'e':		/* option with argument */
			printf("%s: got 'e' option, ", argv[0]);
			printf("argument '%s'\n", optarg);
			break;
		case 'x':		/* option with optional argument */
			printf("%s: got 'x' option, ", argv[0]);
			if (optarg == NULL)
				printf("but no argument to it\n");
			else
				printf("argument '%s'\n", optarg);
			break;
		case '?':		/* error */
			break;
		default:		/* should never happen */
			fprintf(stderr, "%s: What in the world . .. . '%c'\n", argv[0], c);
			break;
		}
	}
	
	/* now print out the non-option arguments */
	for(i = optind; i < argc; i++)
		printf("Command non-option argument '%s'\n", argv[i]);

	/* bye-bye! */
	return(0);
}



UC Davis sigil
Matt Bishop
Office: 2209 Watershed Sciences
Phone: +1 (530) 752-8060
Email: mabishop@ucdavis.edu
ECS 36A, Programming & Problem Solving
Version of April 2, 2024 at 12:13PM

You can get the raw source code here.

Valid HTML 4.01 Transitional Built with BBEdit Built on a Macintosh