C++ Topic
Command Line Processing
Invoking a Program with Command-Line Arguments
For those of you who have worked in Unix or a Command Prompt window under Windows, you have probably
entered a command such as:
cd assignment1
i.e., a command to change the current working directory to assignment1
. The above coomand
actually consists of two components:
- The name of the command (program)
- In this instance,
cd
-- for change directory
- 0 or more arguments which provide additional information to the program
- In our case there is a single argument --
assignment1
--the new current working directory
- As further examples,
- The command
ls
in Unix lists the contents of the current directory (same as the dir
command in Windows).
This command takes no argments.
- The command
cp oldfile newfile
in Unix copies oldfile
to newfile
. This program takes 2 arguments.
Running the command can thus be thought of as analogous to calling a function-- in both cases
- There is a name
- a program name or a function name
- There are one or more arguments/parameters
This is not a coincidence-- in essence your program is viewed by the operating system as just another
function to be called. There obviously is more going on than a simple function call within a program:
- the program must be loaded into memory
- there must be some way for the OS to determine where the program should begin executing
but eventually the OS does indeed make a function call to the program's entry point (which for our purposes is
the main
function).
(As an aside, similarly, the program returns to the OS in much the same way, as can be seen from the
return
statement in main
. The return value is information passed back by the program to
the OS about the success/failure of the program, and is called the program exit status.)
Thus, we see that a program can be invoked with arguments that provide information to the program from the
user. We call these command line arguments.
In order for this information to be of any value to the program, we must be able to access the command line
arguments from within the program.
Accessing the Command Line Arguments From the Program
As we saw above, the command line consists of
- the program name
- 0 or more arguments
The user types the program name and arguments on the command line, and the operating system then parses
the command line, breaking it up to it individual parts-- the program name and each argument (where again, for our purposes,
the arguments are separated by whitespace). Each of thses components-- the program name and the individual arguments-- are
treated as a C-like string (char *
) by the OS, placed into an array of such string (i.e., char *[]
or, equivalently, char **