In this tutorial you will learn about the C Command Line Arguments and its application with practical example.
In C Programming Language we have built-in support for “Command Line arguments”. Command-line arguments allow us to pass the parameters to the C Program’s main() function when they are executed. We can pass the parameters from the command line itself.
Below is the prototype for main() when it is supposed to accept command-line arguments –
syntax:
1 2 3 4 |
int main(int argc, char *argv[]) { ... } |
There are two parameters passed to the main() function.
- int argc
- char *argv[]
The first parameter, argc is an integer that is used to define the number of parameters passed to main(), and the second parameter is argv, is an array of pointers to character strings which is consist of the list of these parameters. Each argument on the command line is separated by
spaces.
1 |
% program-name parameter_1 parameter_2 parameter_3 ... parameter_n |
The program name will be stored in the first item in argv, followed by the list of the parameters. If the program name is followed by n parameters there will be n + 1 element in argv, ranging from argv[0] to argv[n]. argc will be automatically set equal to n + 1.
Example :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
/* hello.c */ /* Program to read and echo data from command line */ #include <stdio.h> int main(int argc, char *argv[]) { int i; for (i = 1; i < argc; i++) printf("%s ", argv[i]); printf("\n"); return 0; } |
Assuming that the executable is called hello.
1 2 3 4 |
% hello Hello world good morning! Hello world good morning! % |