Command Line Arguments - C Programming

The arguments that we pass on to main() at the command prompt are called command line arguments. The full declaration of main looks like this:

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

The function main() can have two arguments, traditionally named as argc and argv. Out of these, argv is an array of pointers to strings and argc is an int whose value is equal to the number of strings to which argv points. When the program is executed, the strings on the command line are passed to main(). More precisely, the strings at the command line are stored in memory and address of the first string is stored in argv[0], address of the second string is stored in argv[1] and so on. The argument argc is set to the number of strings given on the command line.

For example

In our sample program, if at the command prompt we give,

filecopy PR1.C PR2.C


argc would contain 3

  • argv[0] - would contain base address of the string "filecopy"
  • argv[1] - would contain base address of the string "PR1.C"
  • argv[2] - would contain base address of the string "PR2.C"

Following is a simple example which checks if there is any argument supplied from the command line and take action accordingly −

#include <stdio.h>
int main( int argc, char *argv[] )  {
   if( argc == 2 ) 
      printf("The argument supplied is %s\n", argv[1]);
   else if( argc > 2 ) 
      printf("Too many arguments supplied.\n");
      printf("One argument expected.\n");

When the above code is compiled and executed with single argument, it produces the following result.

argumenttest.exe testing
The argument supplied is testing

If you are using Turbo C++ compiler, checkout this tutorial - How to Pass Command Line Arguments in Turbo C++

Results of Parsing Command Lines

The following table shows example input and expected output, demonstrating the rules in the preceding list.

Command-Line Input argv[1] argv[2] argv[3]
"abc" d e abc d e
a\\b d"e f"g h a\\b de fg h
a\\\"b c d a\"b c d
a\\\\"b c" d e a\\b c d e

Related Article