So far we have using main with an empty pair of brackets. But like any other function it is possible to pass argument or parameters to main when it starts executing i.e. at runtime. These arguments are called command line arguments because they are passed to main() from the command line during execution.
main(int argc, char * argv[])
{ -------
-------
}
int argc: Argument count which is the number of command line arguments that are passed to function main().
char *argv[]: argument vector it is an array of pointer each pointing to a command line argument.
i. The subscripts for argv[] are 0 to argc – 1.
ii. argv[0] is the name of the executable file of the program (./a.out).
It is not necessary to use the words argc and argv. Any other identifiers can be used. The arguments can have to be separated by white spaces.
Example : Consider a program“Display.c” which displays the command line arguments on the screen. If the command given is given as Display Argument 10 abcd
The output will be : Argument 10 abcd
For this example, argc = 4 and the arguments will be stored as shown below. argv[0] is the name of the program. argv[1] to argv[3] store the actual command line arguments which are passed.
Note: In Linux, the command will be: #./a.out Argument10 abcd
C Program using Command Line Arguments Display command line arguments
#include<stdio.h>
main(int argc, char *argv[])
{
int i;
for(i=0; i<argc; i++)
printf(“%s\t”, argv[i]);
}
Display all command line arguments in reverse order.
#include<stdio.h>
main(int argc, char *argv[])
{
while(- - argc>=0)
printf(“%s”,argv[argc]);
}
Program which replaces all occurrences of a character in a string by another character
#include<stdio.h>
main(int argc, char *argv[])
{ int i;
char ch1, ch2, str[80];
if(argc !=4)
{ printf(“invalid number of arguments”);
printf(“usage - <progname><string><character><character>”);
exit(0);
}
strcpy(str, argv[1]);
ch1=argv[2] [0];
ch2=argv[3] [0];
for(i =0; str[i]!=’\0’;i++)
if(str[i] ==ch1)
str[i]=ch2;
printf(“the replace string is %s”, str);
}
Advantages of command line arguments
Arguments can be supplied during runtime. Therefore, the program can accept different arguments at different times.
There is no need to change the source code to work with different input to the program.
By using command line arguments, the program can be run with different file names every time since the code in the program will refer to them using argv[].
There’s no need to recompile the program since the source code is not changed.
Comments
Post a Comment
Please give us feedback through comments