Command Line Arguments in C

Preview




Command Line Arguments in C

In C language, it is possible to accept command line arguments. Command-line arguments are providing by typing name of program followed by arguments at command prompt. To use command line arguments in our program, we must declare the main() function which accepts two arguments as follows:

  • First argument specifies the number of command line arguments
  • Second argument specifies the list of all the values passed at command line.

The full declaration of main() with command line arguments looks like:

int main ( int argc, char *argv[] )

argc specifies the number of arguments. It is the number of arguments passed into the program from the command line including the name of the program.

argv is the array of character pointers which contains the list of all the arguments. argv[0] is the name of the program. After that, every element is a command line argument. We can use each argv element just like a string.

Program to demonstrate the use of command line arguments.
#include <stdio.h>
int main ( int argc, char *argv[] )
{
int i;
printf(“Command line arguments are”);
for(i=0;i<argc;i++)
{
printf(“\n%s”, argv[i]);
}
return(0);
}




Steps to run the above program on Turboc are:

Suppose name of the program is COMMARG.C

  1. Compile the program and make its executable.
  2. Open file menu and select Dos Shell.
  3. At the command prompt type the following line:

commarg i love india

The output of the program would be :

Command line arguments are

C:\TCC\COMMARG.EXE

i

love

india

 Tips and Tricks

  • Command Line arguments can be used to provide some value to the program through which the program execution can be altered.
  • Most common use of command line arguments is to provide file name at run time whose contents are to be viewed or to provide filenames such that contents of one file can be copied to another file.

 Best Books of C

Lesson tags: Command Line Arguments in C, Test Your Knowledge in c, TIPS and tricks in c
Back to: C Programming Language