Command line arguments in C:
main() function of a
C program accepts arguments from command line or from other shell
scripts by following commands. They are,
- argc
- argv[]
argc - Number of arguments in the command line including program name
argv[] – This is carrying all the arguments
argv[] – This is carrying all the arguments
- In real time application, it will happen to pass arguments to the main program itself. These arguments are passed to the main () function while executing binary file from command line.
- For example, when we compile a program (test.c), we get executable file in the name “test”.
- Now, we run the executable “test” along with 4 arguments in command line like below.
./test this is a program
Where,
argc = 5
argv[0] = “test”
argv[1] = “this”
argv[2] = “is”
argv[3] = “a”
argv[4] = “program”
argv[5] = NULL
argv[0] = “test”
argv[1] = “this”
argv[2] = “is”
argv[3] = “a”
argv[4] = “program”
argv[5] = NULL
Example program for argc() and argv() functions in C:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) // command line arguments
{
if(argc!=5)
{
printf("Arguments passed through command line " \
"not equal to 5");
return 1;
}
printf("\n Program name : %s \n", argv[0]);
printf("1st arg : %s \n", argv[1]);
printf("2nd arg : %s \n", argv[2]);
printf("3rd arg : %s \n", argv[3]);
printf("4th arg : %s \n", argv[4]);
printf("5th arg : %s \n", argv[5]);
return 0;
}
Output:
|
Program name : test
1st arg : this 2nd arg : is 3rd arg : a 4th arg : program 5th arg : (null) |






0 comments:
Post a Comment