Skip to main content

30. Command Line Arguments

 

Command Line Arguments in C

The arguments passed from command line are called command line arguments. These arguments are handled by main() function. Command line arguments are used to supply parameters to the program when it is invoked. It is mostly used when we need to control our program from the console. These arguments are passed to the main() method.

To support command line argument, we need to change the structure of main() function as given below:

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

Here argc counts the number of arguments. It counts the file name as the first argument.
The argv[] contains the total number of arguments. The first argument is the file name always.

#include <stdio.h>
int main(int argc, char const *argv[])
{
   printf("Program name is: %s\n", argv[0]);
   if(argc < 2)
   printf("No argument passed through command line.\n");
   else
   printf("First argument is: %s\n", argv[1]);
   return 0;
}

If we simply run this program, then

Output :

Program name is: S:\C\37.exe
No argument passed through command line.

If we run this program as follows in Linux:

./S:\C\37 hello

And in Windows from command line

S:\C\37.exe hello

Output :

Program name is: S:\C\37.exe
First argument is: hello

If we pass many arguments, it will print only one. But, if we pass many arguments within double quotes, all arguments will be treated as a single argument only. In this program, we are printing only argv[1], that is why it is printing only one argument.

Comments