Unit 4 Command Line Arguments
Unit 4 Command Line Arguments
It is possible to pass some values from the command line to your C programs when they are executed.
These values are called command line arguments and many times they are important for your program
especially when you want to control your program from outside instead of hard coding those values
inside the code.
The command line arguments are handled using main() function arguments. To pass command line
arguments, we typically define main() with two arguments.
int main(int argc, char *argv[]) { /* ... */ }
where argc refers to the number of arguments passed, and argv[] is a pointer array which points to each
argument passed to the program. Following is a simple example which checks if there is any argument
supplied from the command line and take action accordingly
#include <stdio.h>
void main(int argc, char *argv[] ) {
Output:
Program name is: program
First argument is: hello
If you pass many arguments, it will print only one.
./program hello c how r u
Output:
Program name is: program
First argument is: hello
But if you pass many arguments within double quote, all arguments will be treated as a single argument
only.
./program "hello c how r u"
Output:
Program name is: program
First argument is: hello c how r u
You can write your program to print all the arguments. In this program, we are printing only argv[1],
that is why it is printing only one argument.