C Command Line

The command line argument is the parameter given to the program after it was called. The command line argument is an important concept in C programming. It is mainly used when you want to control your program from outside. Command line arguments are passed to the main () method.

Command Line Argument Properties:

  • They are passed to the main () function.
  • These are the parameters/arguments provided to the program when called.
  • They are used to control the program from the outside instead of rigidly encoding these values inside the code.
  • argv [argc] – NULL pointer.
  • argv [0] contains the name of the program.
  • argv [1] points to the first command-line argument and argv [n] to the last argument.

Syntax:

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

Here, argc calculates the number of arguments on the command line, and argv [] is an array of pointers that stores char pointers that point to arguments passed to the program.

Example for Command Line Argument

#include <stdio.h>
#include <conio.h>

int main(int argc, char *argv[])
{
    int i;
    if( argc >= 2 )
    {
        printf("The arguments supplied are:\n");
        for(i = 1; i < argc; i++)
        {
            printf("%s\t", argv[i]);
        }
    }
    else
    {
        printf("argument list is empty.\n");
    }
    return 0;
}

Remember that argv [0] contains the name of the program, and argv [1] points to the first command line argument, and argv [n] gives the last argument. If no argument is given, argc will be 1.

Leave a Reply

Your email address will not be published. Required fields are marked *

Shopping cart