C: getopt Example: Accessing command line arguments

The simplest way to work with command line arguments is to use the getopt() function. To understand more about it, first let’s see a command which can calculate the area and perimeter of a rectangle

  1. rectangle a -l 12 -b 34: will calculate the area of the rectangle
  2. square p -l 12 -b 34: will calculate the perimeter of the rectangle
  3. rectangle ap -l 12 -b 34: will calculate the area and perimeter of the rectangle

As we can see, some options take arguments and some do not. Here a and p do not take any argument. But -l and -b take the arguments (number) for length and breadth respectively.

So to distinguish them, getopt provides a mechanism. All the options that require argument will be preceded by a : (colon).

The following program shows this

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

/** Program to calculate the area and perimeter of 
 * a rectangle using command line arguments
 */
void print_usage() {
    printf("Usage: rectangle [ap] -l num -b num\n");
}

int main(int argc, char *argv[]) {
    int option = 0;
    int area = -1, perimeter = -1, breadth = -1, length =-1;

    //Specifying the expected options
    //The two options l and b expect numbers as argument
    while ((option = getopt(argc, argv,"apl:b:")) != -1) {
        switch (option) {
             case 'a' : area = 0;
                 break;
             case 'p' : perimeter = 0;
                 break;
             case 'l' : length = atoi(optarg); 
                 break;
             case 'b' : breadth = atoi(optarg);
                 break;
             default: print_usage(); 
                 exit(EXIT_FAILURE);
        }
    }
    if (length == -1 || breadth ==-1) {
        print_usage();
        exit(EXIT_FAILURE);
    }

    // Calculate the area
    if (area == 0) {
        area = length * breadth;
        printf("Area: %d\n",area);
    }

    // Calculate the perimeter
    if (perimeter == 0) {
        perimeter = 2 * (length + breadth);
        printf("Perimeter: %d\n",perimeter);
    }
    return 0;
}