command line arguments It is possible to pass some values from the command line to your C programs when they

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 )

} else if( argc > 2 ) { printf("Too many arguments supplied.#include <stdio. argv[1]).h> int main( int argc. char *argv[] ) { if( argc == 2 ) { printf("The argument supplied is %s\n". } } .\n").\n"). } else { printf("One argument expected.

The code is: #include <stdio.Below is a simple calculator which takes as arguments two numbers and prints the sum. char *argv[]) { if ( argc != 3) { printf("Usage:\n %s Integer1 Integer2\n".argv[0]).h> int main(int argc. } .

atoi(argv[1])+atoi(argv[2] )).exe Usage: ArgumentCalculator.argv[ 1].argv[2].exe Integer1 Integ er2 C:\> . } Now lets explain the code: line 4 : we check if the user passed two arguments to the program. } return 0.else { printf("%s + %s = %d\n". so we need two more. We actually need two arguments but in C the first argument ( argv[0] ) is the name of our program. 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 C:\>ArgumentCalculator.

exe 123456789 9 87654322 123456789 + 987654322 = 1111111111 C:\> .C:\>ArgumentCalculator.

Sign up to vote on this title
UsefulNot useful