Program Arguments


Some programs need to access the arguments that were specified to them on the commandline. For example, emacs can take a filename:

% emacs myfile.txt

or you might give ls a flag and a directory:

% ls -l hw2

Here, "myfile.txt", "-l" and "hw2" are all program arguments. Arguments are typically separated by spaces on the commandline.


The way that a program can access its arguments is via parameters to the function main(). So far, we have been declaring our main()'s without parameters:

int main()
{
  ...

If we want access to the program's arguments, we need 2 parameters (in this exact order):

int main(int argc, char *argv[])
{
  ...

Here,


Aside: Ok, we know that array parameters are really just pointers, but for simplicity, let's think of argv as an array.

So, suppose main()'s parameters are declared as above and we ran such a program:

% path/a.out this  that another

then argc and argv would be as follows:

 argc
 -----
 | 4 |
 -----

 argv
 -----
 |   |    ----------------------------------------------
0| --+--> | p | a | t | h | / | a | . | o | u | t | \0 |
 |   |    ----------------------------------------------
 -----
 |   |    ----------------------
1| --+--> | t | h | i | s | \0 |
 |   |    ----------------------
 -----
 |   |    ----------------------
2| --+--> | t | h | a | t | \0 |
 |   |    ----------------------
 -----
 |   |    ----------------------------------
3| --+--> | a | n | o | t | h | e | r | \0 |
 |   |    ----------------------------------
 -----


Note: Any path specified on the commandline (along with the program name) to run the executable is often retained (but this depends on the operating system).

So, for example, the word "another" will be in argv[3].

Special Parts of Commandline

Redirection (and some other special operating system things typed on the commandline) don't count as program arguments. In other words, the program a.out below:
% a.out foo < infile > outfile

will receive 2 arguments: "a.out" (the command name) and "foo". The "< infile" and "> outfile" parts are processed by the operating system before the program is run.


BU CAS CS - Program Arguments
Copyright © 1993-2000 by Robert I. Pitts <rip at bu dot edu>. All Rights Reserved.