Friday, July 29, 2016

C Basics - Command Line Arguments in C

In, windows with MinGW, command line, we supply a.exe command to execute a program. It is possible to pass some values from the command line to C programs. These values are called command line arguments.

The command line arguments are handled using main() function arguments where argc refers to the number of arguments passed, and argv[] is a pointer array which points to each argument passed to the program.

Following program list out the command line arguments.

#include <stdio.h>

int main( int argc, char *argv[] )  {

   int i; 
   
   printf("Number of command line argument(s) supplied is: %d\n", argc);
   
   for ( i = 0; i < argc; i++ ) {
     printf("Argument No.%d is: %s\n",i, argv[i]);
   }
   return 0;
}
Try the following in command line.

a.exe
a.exe test
a.exe test1 test2
a.exe “test program” 

It should be noted that argv[0] holds the name of the program itself and argv[1] is a pointer to the first command line argument supplied, and *argv[n] is the last argument. If no arguments are supplied, argc will be one, and if you pass one argument then argc is set at 2.

The arguments are separated by a space. If argument itself has a space then you can pass such arguments by putting them inside double quotes ("").

The following program performs addition, subtraction, multiplication and division of two integer numbers using command line arguments.

#include <stdio.h>

int main( int argc, char *argv[] )  {

   int a,b,c,d;
   float e;
   int i; 
   
   printf("Number of command line argument(s) supplied is: %d\n", argc);
   
   for ( i = 0; i < argc; i++ ) {
  printf("Argument No.%d is: %s\n",i, argv[i]);
   } 
   if(argc == 1){
 printf("Three more arguments expected.\n");
   }else if(argc == 2){
 printf("Two more arguments expected.\n");
   }else if(argc == 3){
 printf("One more argument expected.\n");
   }else if(argc == 4){
 sscanf( argv[1], "%d", &a );
 sscanf( argv[2], "%d", &b );  
 sscanf( argv[3], "%d", &c );
 if(a == 1){
  printf("Performing Addition Operation\n");
  d = b + c;
  printf("Addition of %d and %d is %d\n", b,c,d);
 }else if (a == 2){
  printf("Performing Subtraction Operation\n");
  d = b - c;
  printf("Subtraction of %d and %d is %d\n", b,c,d);   
 }else if (a == 3){
  printf("Performing Multiplication Operation\n");
  d = b * c;
  printf("Subtraction of %d and %d is %d\n", b,c,d);   
 }else if (a == 4){
  printf("Performing Division Operation\n");
  e = (float)b / (float)c;
  printf("Division of %d and %d is %f\n", b,c,e);   
 }else{
 printf("Invalid operation requested. Check argument 2 value!\n");
 }
   }else{ 
 printf("Too many arguments supplied.\n");
   }
   return 0;
}
Try the following in command line.

a.exe 1 2 3
a.exe 2 2 3 



Related topics:
Functions in C   |   Function Definition and Declaration in C   |   Calling a Function in C   |   Recursion in C   |   Variable Arguments in C

List of topics: C Programming

No comments:

Post a Comment