Command line arguments:
Generally command line arguments are the parameters taken by the main function of any c language program. The main takes two arguments. First one is the number of arguments available on the command line including the program name and the user specified arguments the second parameter is the character array which originally holds the typed arguments. Characters between the two spaces are interpreted as the argument on the command line. For example on the command line we typed
code.exe visual studio 2010
then the code.exe is the program we wish to execute and the visual is the second command line argument studio is the third and 2010 is the fourth. The main function which takes the command line arguments takes two forms like
main(int argc, char* argv[])
main(int argc, char** argv)
In the first form the argument array is specified with the single pointer and the array. In the second one it is specified as the double pointer. Generally when the array is declared the array name acts as the pointer to the first element in the array. In the second case we used double pointer so there is no need of the array.
To access the command line arguments we can fallow the normal array elements accessing rules. But one must remember that the first command line argument is the currently executing program name so if we want to access the user intentionally typed arguments we have to start from the second array element. That is index is 1. The fallowing code snippets help to visualise the command line arguments easily.
#include "stdafx.h"
#include <conio.h>
void main(int argc, char* argv[])
{
int num_arg=argc,i;
printf("Number of arguments on the commandline are %d",num_arg);
for(i=0;i<num_arg;i++)
{
printf("The %d command line argument is %s",i+1,argv[i]);
puts("\n");
}
_getch();
}
the for loop in the code prints the arguments on the command line. one thing we have to remember is the fourth argument 2010 is also considered as the character array so if we want the numerical value we have to convert back to the integer value using some conversion available in the c standard library like "atoi" function. in the output windows we can see the first command line argument is the absolute path of the currently executing program.
#include "stdafx.h"
#include <conio.h>
void main(int argc, char** argv)
{
int num_arg=argc,i;
printf("Number of arguments on the commandline are %d",num_arg);
for(i=0;i<num_arg;i++)
{
printf("The %d command line argument is %s",i+1,argv[i]);
puts("\n");
}
_getch();
}
the second example is another code demonstrating the use of command line arguments. The path for the file to open is passed as the second command line argument of index one and it is used to save the command line arguments in it.
No comments:
Post a Comment