Categories: C

Command Line Argument

When your C programs are run, you can pass some values from the command line to them. These values are known as command-line arguments, and they are frequently useful for your program, particularly when you want to control it from the outside rather than hard-coding those values into the code.

The command-line arguments are handled by the main() function arguments, where argc denotes the number of arguments passed and argv[] denotes a pointer array containing each argument passed to the program.

Example:
#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");
   }
   else {
      printf("One argument expected.\n");
   }
}

When the above code is compiled and run with only one argument, the following is the result.

$./a.out testing
The argument supplied is testing

When the above code is compiled and run with two arguments, the following result is obtained.

$./a.out testing1 testing2
Too many arguments supplied.

When the above code is compiled and run without any arguments, the following result is obtained.

$./a.out
One argument expected

Note: also read about the Dynamic Memory Allocation

Follow Me

If you like my post please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Share
Published by
Rabecca Fatima

Recent Posts

Find Intersection of Two Singly Linked Lists

You are given two singly linked lists that intersect at some node. Your task is…

3 months ago

Minimum Cost to Paint Houses with K Colors

A builder plans to construct N houses in a row, where each house can be…

4 months ago

Longest Absolute Path in File System Representation

Find the length of the longest absolute path to a file within the abstracted file…

4 months ago

Efficient Order Log Storage

You manage an e-commerce website and need to keep track of the last N order…

5 months ago

Select a Random Element from a Stream

You are given a stream of elements that is too large to fit into memory.…

5 months ago

Estimate π Using Monte Carlo Method

The formula for the area of a circle is given by πr². Use the Monte…

5 months ago