Login

Username:

Password: 

Join us Now |  Forgot Password? | Forgot UserName?

C

Learn step by step



C-Command line arguments

main() function of a C program can accept arguments from command line or from other shell scripts by the following commands.

  • argc
  • argv[]

where,

argc-Carry number of arguments in the command line including program name

argv[]-This 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.
  • Example, when we compile a program (for example "test.c"), we get an executable file named "test".
  • Then, we run the executable "test" along with 4 arguments in command line given 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

Program for argv() and argc() 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)


Related Videos