Tuesday 30 January 2018

Command Line Arguments

Command Line Arguments

               We know that every C program has atleast one function i.e main( ). Similar to other functions, main( ) can also take arguments. These arguments are known as command line arguments and they are passed to the program at runtime. main( ) actually takes two arguments :
int argc is the argument count i.e the number of arguments passed to the program.
char *argv[ ] is an array of strings where each string is a command line argument. The first string i.e argv[0] is the name of the program. Thus, there is atleast one argument always passed to main.

Following program illustrates the use of command line arguments :

----------------------------------------------------------------------------------------------------------------------------



----------------------------------------------------------------------------------------------------------------------------

Assuming we are on linux system and the program is saved as prog.cpp
Compile : gcc -o prog prog.cpp
Executable is generated with name prog
Run : ./prog Hello World
where the command line arguments are " ./prog " , " Hello " and " World "
Output :
No. of arguments : 3
argv[0] = ./prog
argv[1] = Hello
argv[2] = World
On a windows system, if you are using some IDEs, there will be some option to input command line arguments. 

No comments:

Post a Comment