C Programming (getopt)
GETOPT(3) Linux Programmer's Manual GETOPT(3)
NAME
getopt, getopt_long, getopt_long_only, optarg, optind, opterr, optopt - Parse
command-line options
SYNOPSIS
#include
int getopt(int argc, char * const argv[],
const char *optstring);
extern char *optarg;
extern int optind, opterr, optopt;
- getopt is repeatedly called to get the next command line option
- optstring is a string indicating the options we are interested in, a colon (:)
after an option indicates that this option is associated with an argument
- optind is the current index into argv
- optarg is a pointer to this options argument, if the option has an argument
- optopt is the currently scanned option
Work in pairs to understand the following examples and then complete the associated exercise.
Exercise
Complete getoptExercise.c which behaves as follows:
it prints the sum of the -x and -y arguments. If the -d option is present, it doubles
the sum. For example:
apps0> gcc -o getoptExercise -Wall getoptExercise.c
apps0> ./getoptExercise -x 12
12
apps0> ./getoptExercise -x 12 -d
24
apps0> ./getoptExercise -x -d
Option -x requires an integer argument.
apps0> ./getoptExercise -y 10 -d -x 12
44
apps0> ./getoptExercise -x 10 -y 12 -d
44
apps0> ./getoptExercise -x 10 -y 12
22