In C programming language, command line arguments are the values that are passed from command line to our program. This allows the user to provide some input to the program at run time. Generally, all the command line arguments are handled by the main() method.
It is passing arguments to the main() method from the command line.
When command line arguments are passed, the main() method receives them with the help of two formal parameters and they are:
- int argc: This is the count of number of arguments passed form the command line.
- char *argv[ ]: It is a character pointer array which is used to store the actual values of command line arguments passed during run time.
Example:
#include <stdio.h>
int main ( int argc, char *argv[ ])
{
if (argc <2)
{
printf("\n Invalid number of arguments passed\n");
return 0;
}
printf("\n Total number of arguments are %d and they are:\n", argc);
for (int i = 0; i < argc; i++)
{
printf("\n %d -- %s\n", i+1, argv[i]);
}
return 0;
}
Output:
In the above example, there are 2 arguments passed that are (Hello, tech-access) but the output shows the number of arguments as 3 because the path of the file is the default argument. Hence the total number of arguments is 3.
Note:
- Always the first argument is the file path
- Only the string values can be passed as command line arguments.
- All the command line argumnets are stored in character pointer array called argv[].
- Total number of command line argumenst including the file path are stored in integer parameter called argc.
Examples to display the sum of all command line arguments:
#include<stdio.h>
int main(int argc, char *argv[]){
int i, n, sum = 0;
if(argc == 1){
printf("\n Please provide command line arguments!!!");
return 0;
}
else{
printf("\n Total number of arguments are:%d and sum of those is: ", argc);
for(i=0; i<argc ; i++){
n = atoi(argv[i]);
sum += n;
}
printf("%d\n", sum);
return 0;
}
}
OUTPUT:
Total number of arguments are: 6 and sum of those is: 150
Categories: C Language
Leave a Reply