What is Command Line Argument ?
In case of command line argument we can pass value from the command line before compiling or executing the program. In general, we input for the program after compiling the program. But here we provide all the inputs before compiling the program. Now here is an example, let’s check it.
C
C
#include <stdio.h>
int main(int argc, char *argv[])
{
int i;
if( argc >= 2 )
{
printf(“The arguments supplied are:\n”);
for(i = 1; i < argc; i++)
{
printf(“%s\t”, argv[i]);
}
printf(“\n%s”,argv[0]);
printf(“\nargc=%d”,argc);
}
else
{
printf(“argument list is empty.\n”);
printf(“%s”,argv[0]);
printf(“\nargc=%d”,argc);
}
return 0;
}
In this program, we can see two things.
argv
argc
What is argc?
argc in Command line argument in C means the total number of arguments passed through command line argument.
If we don’t pass any argument in command line then argc value will be 1 as the file location of the executing program will be passed and will be stored into argv[0].
Suppose, if you pass two arguments then your argc value is 3 as 2 for your arguments and 1 for the location of the executing program.
What is argv?
argv stands for argument value. argv in command line argument in C is a pointer array which points to each argument passed to the program.
argc stands for argument count and argv stands for argument values. These are variables passed to the main function when it starts executing.
Here, we check if the value of argc is equal or greater than 2, only then we will print the value of the passing arguments. You can also check the executing file location and the value of argument count.
Otherwise, it will show “argument list is empty” and also the location of the executing file due to printing argv[0] and the value of argument count for printing argc.
C
C
#include
#include
int main(int argc, char *argv[])
{
int x;
float y;
char z;
double d;
if( argc >= 2 )
{
x=atoi(argv[1]);
sscanf(argv[2],”%f”,&y);
sscanf(argv[3],”%c”,&z);
sscanf(argv[4],”%lf”,&d);
printf(“\n argv[1]=%d”,x);
printf(“\n argv[2]=%f”,y);
printf(“\n argv[3]=%c”,z);
printf(“\n argv[4]=%lf”,d);
}
else
{
printf(“\n Empty list”);
}
return 0;
}