Command Line Arguments in C Programming

An application takes inputs in various ways. It can ask for input from user while it is running. It can read something from file or socket. Another way is, we can give inputs in time of starting the application in the form of command line arguments. For example, when we run Linux commands we give several options as command line arguments to application . Here we’ll see how to write a C program that will take command line arguments.

#include <stdio.h>

int main( int argc, char *argv[] )  {
  int i = 0;
  printf("Application name: %s\n\n", argv[0]);
  
  printf("Command line arguments:\n");
  for(i = 1; i < argc; i++) {
    printf("Argument %d: %s\n", i, argv[i]);
  }
  
  return 0;
}

Here the main() function will have two parameters, argc and argv. When the program starts, argc contains the number of arguments passed, including the application name. The other parameter, argv, is an array of string. It holds all the command line arguments. The first element is always the application name.

Here is the output of the above program.

Command Line Arguments Output

Author: Srikanta

I write here to help the readers learn and understand computer programing, algorithms, networking, OS concepts etc. in a simple way. I have 20 years of working experience in computer networking and industrial automation.


If you also want to contribute, click here.

Leave a Reply

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

0
0
0
0
1
0