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

What is object oriented design patterns

A design pattern is a reusable solution to a commonly occurring problem in software design. They…

2 months ago

Factory Method Design Pattern in OODP

Factory Method is a creational design pattern that deals with the object creation. It separates…

2 months ago

Find Intersection of Two Singly Linked Lists

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

8 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…

8 months ago

Longest Absolute Path in File System Representation

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

8 months ago

Efficient Order Log Storage

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

9 months ago