Home » Posts tagged 'command-line-argument'

# Tag Archives: command-line-argument

## Command Line Argument in C Programming

In a C programming often a situation may come where we want to pass the information into a program during the execution of program. These values are called Command Line Arguments(CLA).

“main()” function handles the command line argument.

Syntax:

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

}

Here, argc refers to the number of arguments passed  and argv[] is a pointer array which points to each argument .

Note:  argv[0] - holds the name of the program

argv[1]- holds the first command line argument, argv[2]- holds the second command line argument and and so on.

If no argument is supplied, argc will be 1

Example: Write a program in a C to take one value from user during execution as a command line argument.

#include int main(int argc, char *argv[] ) { printf(“Program name is: %s = “, argv[0]); printf(“\n Command line argument is: %s”, argv[1]); return 0; }

Note: Suppose above program name is “CLA”.

Run this program as follows in Linux:

./CLA hello

Here hello is a command line argument.

Run this program as follows in Windows from command line:

program.exe  hello

Here hello is a command line argument.

Output:

Program name is: CLA
First argument is: hello

Example: Write a program in a C to take 4 value from user during execution as a command line argument.

OUTPUT

Note: Suppose above program name is “CLA”.

Run this program as follows in Linux:

./CLA  this is IT department

Here this is IT department are 4 command line argument.

OUTPUT

Program name : CLA
1st arg : this
2nd arg : is
3rd arg : IT
4th arg : department
5th arg : (null)

Managed by MochaHost - Fast & Easy WordPress Hosting