Command Line Arguments
Command Line Arguments
are executed. These values are called command line arguments Many times they are important for your program specially when you want to control your program from outside instead of hard coding those values inside the code. 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.
In this simple example we will see how to use the command line arguments in our C programs. Well, we all noticed that main() get two parameters. int main(int argc, char *argv[]); argc is an integer representing the size of argv[] argv is a table of pointer to chars ( Strings )
#include <stdio.h> int main( int argc, char *argv[] ) { if( argc == 2 ) { printf("The argument supplied is %s\n", argv[1]); } else if( argc > 2 ) { printf("Too many arguments supplied.\n"); } else { printf("One argument expected.\n"); } }
Below is a simple calculator which takes as arguments two numbers and prints the sum. The code is:
#include <stdio.h> int main(int argc, char *argv[]) { if ( argc != 3) { printf("Usage:\n %s Integer1 Integer2\n",argv[0]); }
else { printf("%s + %s = %d\n",argv[ 1],argv[2], atoi(argv[1])+atoi(argv[2] )); } return 0; } Now lets explain the code: line 4 : we check if the user passed two arguments to the program. We actually need two arguments but in C the first argument ( argv[0] ) is the name of our program, so we need two more. line 5 : If the user didn't pass two arguments we print the usage of our program and exit line 8 : Using atoi() function we convert pointers to char (string) to decimal numbers and display their sum