Wednesday, 8 January 2014

C Programming Language Tutorial XVII – Commandline Argument

Command Line Arguments
Parameters pass to a program by command prompt treat as command line arguments. The parameters are generally used to pass some useful information to the program. An argument is the information that follows the program name on the command line of the operating system.
Till now we have used the main method in a very limited form. main() method can take arguments just like any other function. main() can take two arguments called argc and argv, and the information contained in the command line arguments is passed to the main method through this arguments, when main method is called by the system for execution.
main(int argc, char *argv[])
The argc argument holds the number of arguments on the command line and is an integer. The value of argc is at least 1 because the name of the program qualifies as the first argument.
The argv parameter is a pointer to an array of character pointers.
When a copy command of DOS is used, the statement given is : copy file1 file2.
Like above statement you can also create your own command by using commandline argument.
Following program is to print and count number of arguments pass to main() function.
#include<stdio.h>
#include<conio.h>
void main(int argc,char *argv[])   //arguments for main()
{
 int cnt;
 clrscr();
 printf("Total arguments = %d\n",argc);   //It counts and print  no. of arguments
 for(cnt=0;cnt<argc;cnt++)
 {
  printf("argv[%d] = %s\n",cnt,argv[cnt]);
 }
 getch();
}
Whenever you complied and execute this program then it will display output as follows:
Total arguments = 1
argv[0] = CARGS.EXE
By default, the programs name is a first argument. Here the above program is saved by cargs.c name. To pass arguments from command prompt you have to run this program on DOS.
If you have a Turboc then follow the steps:
  1. File->DOS Shell
  2. C:\TCC>cargs.exe Apple Mango
  3. Total arguments = 3
argv[0] = C:\TCC\CARGS.EXE
argv[1] = Apple
argv[2] = Mango

No comments:

Post a Comment