Command Line
Command Line
arguments
Command line arguments
• Here is the syntax of main() function with command line
arguments
• int main( int argc, char *argv[] ) Here,
• int argc - is the local variable name (you can use any name
here), basically argc is the argument count, it will contain
the total number of arguments given through the
command line (including program name).
• char *argv[ ] - An array of strings, that will contain the
strings (character arrays) which is written on the command
line.
• Consider the following statement
• ./main Mike 27 "New Delhi" India
• Here, total number of arguments will be 5.
Department of CSE 2
Example
#include<stdio.h>
int main(int argc, char* argv[ ])
{
int iLoop;
printf("\nTotal number of arguments : %d",argc);
printf("\nArguments are :\n");
for(iLoop=0;iLoop < argc; iLoop++)
{
printf("%s\t",argv[iLoop]);
}
printf("\n");
return 0;
}
Department of CSE 3
Sum of two Integers
#include <stdio.h>
#include<stdlib.h>
int main(int argc, char *argv[])
{
int a,b,sum;
if(argc!=3)
{
printf("please use \"prg_name value1 value2 \"\n");
return -1;
}
a = atoi(argv[1]);
b = atoi(argv[2]);
sum = a+b;
printf("Sum of %d, %d is: %d\n",a,b,sum);
return 0;
}
Department of CSE 4