Programming 59
reader@hacking:~/booksrc $ gcc -o commandline commandline.c
reader@hacking:~/booksrc $ ./commandline
There were 1 arguments provided:
argument #0 - ./commandline
reader@hacking:~/booksrc $ ./commandline this is a test
There were 5 arguments provided:
argument #0 - ./commandline
argument #1 - this
argument #2 - is
argument #3 - a
argument #4 - test
reader@hacking:~/booksrc $
The zeroth argument is always the name of the executing binary, and
the rest of the argument array (often called an argument vector) contains the
remaining arguments as strings.
Sometimes a program will want to use a command-line argument as an
integer as opposed to a string. Regardless of this, the argument is passed in
as a string; however, there are standard conversion functions. Unlike simple
typecasting, these functions can actually convert character arrays containing
numbers into actual integers. The most common of these functions is atoi(),
which is short for ASCII to integer. This function accepts a pointer to a string
as its argument and returns the integer value it represents. Observe its usage
in convert.c.
convert.c
#include <stdio.h>
void usage(char *program_name) {
printf("Usage: %s
exit(1);
}
int main(int argc, char *argv[]) {
int i, count;
if(argc < 3) // If fewer than 3 arguments are used,
usage(argv[0]); // display usage message and exit.
count = atoi(argv[2]); // Convert the 2nd arg into an integer.
printf("Repeating %d times..\n", count);
for(i=0; i < count; i++)
printf("%3d - %s\n", i, argv[1]); // Print the 1st arg.
}
The results of compiling and executing convert.c are as follows.
reader@hacking:~/booksrc $ gcc convert.c
reader@hacking:~/booksrc $ ./a.out
Usage: ./a.out