Command Line Argument
Command line arguments are arguments for the main function. main is basically a function
It can receive arguments like other functions. The ‘calling function’ in this case is the operating
system, or another program
'main' prototype
int main(int argc, char* argv[])
When we want main to accept command line arguments, we must define it like this
• argc holds the number of arguments that were entered by the caller
• argv is an array of pointers to char – an array of strings – holding the text values of the
arguments. The first argument is always the program’s name
Consider the following program
/* This program displays its command-line arguments */
#include <stdio.h>
int main(int argc, char *argv[])
{
int i;
printf("The program's command line arguments are: \n");
for (i = 0; i < argc; ++i) {
printf("%s\n", argv[i]);}
return 0;
}
If this program is compiled and run (using command prompt)
$ gedit cmdProgram.c
$ gcc -o cmdProgram cmdProgram.c
$ ./cmdProgram I love C program
======output=========
The program's command line arguments are:
./cmdProgram
I
love
C
program
$
So the first argument argv[ ], that is argv[0] is always the program name, the other
arguments followed from argv[1], argv[2], etc, argc giving the total number of arguments
In windows you can specify these arguments directly, by using the Windows console (Start
Run…, then type ‘cmd’ and drag the executable into the window. Then type the arguments
and <Enter>)
Helper Functions: atoi/atof
int atoi(char s[]);
double atof(char s[]);
Command line arguments are received in the form of strings
These functions are used when we want to transform them into numbers
For example – atof(“13.5”) returns the number 13.5. To use atoi you must include :
#include <stdlib.h>
Example
Write a program that accepts two numbers as command line arguments, representing a
rectangle’s height and width (as floating-point numbers). The program should display the
rectangle’s area and perimeter
Solution
int main(int argc, char* argv[])
{
double width, height;
if (argc != 3) {
printf("Wrong number of arguments!\n");
return 1;
}
width = atof(argv[1]);
height = atof(argv[2]);
printf("The rectangle's area is %g\n", width * height);
printf("The rectangle's perimeter is %g\n",2 * (width + height));
return 0;
}