% program-name parameter_1 parameter_2 parameter_3 ... parameter_nThe program name will be stored in the first item in argv, followed by each of the parameters. Hence, if the program name is followed by n parameters there will be n + 1 entries in argv, ranging from argv[0] to argv[n]. Furthermore, argc will be automatically set equal to n + 1.
The program listed below is a simple illustration of the use of command line parameters: it simply echoes all of the parameters passed to it.
/* repeat.c */ /* Program to read and echo data from command line */ 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 repeat, the typical output from this program is as follows:
% repeat The quick brown fox jumped over the lazy hounds The quick brown fox jumped over the lazy hounds %
Suppose that one or more of the parameters passed to a given program are numbers. As we have seen, these numbers are actually passed as character strings. Hence, before they can be employed in calculations, they must be converted into either type int or type double. This can be achieved via the use of the functions atoi() and atof() (the appropriate header file for these functions is stdlib.h). Thus, int atoi(char *ptr) converts a string pointed to by ptr into an int, whereas double atof(char *ptr) converts a string pointed to by ptr into an double. The program listed below illustrates the use of the atof() function: it reads in a number passed as a command line parameter, interprets it as a temperature in degrees Fahrenheit, converts it to degrees Celsius, and then prints out the result.
/* ftoc.c */ /* Program to convert temperature in Fahrenheit input on command line to temperature in Celsius */ #include <stdlib.h> #include <stdio.h> int main(int argc, char *argv[]) { double deg_f, deg_c; /* If no parameter passed to program print error message and exit */ if (argc < 2) { printf("Usage: ftoc temperature\n"); exit(1); } /* Convert first command line parameter to double */ deg_f = atof(argv[1]); /* Convert from Fahrenheit to Celsius */ deg_c = (5. / 9.) * (deg_f - 32.); printf("%f degrees Fahrenheit equals %f degrees Celsius\n", deg_f, deg_c); return 0; }Assuming that the executable is called ftoc, the typical output from this program is as follows:
% ftoc 98 98.000000 degrees Fahrenheit equals 36.666667 degrees Celsius %