Topic : Command Line Arguments
Author : David Beech
Page : 1

Command Line Arguments


Introduction
There are many occasions when you have used command lines with arguments in both UNIX and DOS systems, now you learn how it is done.

The command arguments are the program arguments, or the arguments to the function main(). Whenever a C++ program is run from a command line the arguments of the command line are available as an argument count, conventionally called argc, and an array of pointers, conventionally called argv, to C-style character strings that contain the arguments. Conventionally argv[0] is the command name so argc is always> 0; argv is a pointer to an array whose individual elements are pointers to arrays of characters; each array of characters is terminated by \0 so that they can be treated as strings.

$ man cc

The example here shows a command line that consists of:

the command or program to run: man
an argument for the program: cc

The argument count is 2, the first argument is man and the second argument is cc. The arguments are a way of passing information to the program without querying the user of the program when it runs. You might be thinking that using command line arguments like this is a nuisance. In fact it is very useful because it enables the program to use input and output redirection and makes the program a candidate for use in automated scripting situations.

Reading the command line arguments
//cmd_line1.cc

#include <iostream>
#include <iomanip>

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

  for (i = 0; i < argc; i++)
   cout << "Argument "
        << setw(4)
        << i << " is "
        << argv[i] << endl;
  return 0;
}


Command line:

$ ./a.out read this line

Output:

Argument    0 is a.out
Argument    1 is read
Argument    2 is this
Argument    3 is line

The line:

main(int argc, char *argv[])

shows that function main() has two arguments, an integer called argc and an array of pointers to char called argv. The second argument argv[] might puzzle you. You might find it easier to think about argv as an array of an array of chars.

Each of the pointers in argv "points" to one of the command line arguments. Index 0 is a pointer to the command itself, index 1 is the next argument and so on.





Tutorial
Exercise 1
Try the example programs first and make sure they work.

Exercise 2
Dealing with C-style strings is quite tedious and should be avoided by all but the most ardent C programmer. Take a copy of example cmd_line1.cc and amend to use the string class which you have been using throughout this course. You need to retain the main function declaration as is - int main(int argc, char *argv[]) - but will need to create dynamic string variables for the command line arguments.

If you get stuck there is a sample answer bellow.

Exercise 3
You know that many UNIX programs use command line arguments, for instance the tar program:

tar xvf myfile.tar

Most of these command line programs offer some help, typically accessible via a help switch:

tar --help

The -- or - indicates that some option follows, in this case a plea for help.

Modify your answer from Exercise 2 so that it looks in the command line for --help and if found runs a function called help() which displays, well, help.

If you get stuck there is a sample answer bellow.




Exercise 2 - Command line arguments

#include <iostream>
#include <iomanip>
#include <string>

main(int argc, char *argv[])
{ int i;
  string *cmdline;

  cmdline = new string[argc];
  if (cmdline != NULL)
   { for (i = 0; i < argc; i++)
      cmdline[i] = argv[i];

     for (i = 0; i < argc; i++)
      cout << "cmd arg "
           << setw(4)
           << i << " is "
           << cmdline[i] << endl;
     delete[] cmdline;
     return 0;
   }
  else
   { cerr << "ERROR: no space."
          << endl;
     return -1;
   }
}


You can see that I have added a variable of type pointer to a string:

  string *cmdline;

and I use the new operator to create an array of strings to hold the command line arguments.

Next I test the value return by the new operation to make sure that memory was allocated. If we received a result NULL then we should stop the program since it will be in an unsafe state. In small programs like this and in the environment you use at present it is unlikely that the machine will run out of memory. However you should ALWAYS check memory allocation when using dynamic variables.

Assuming that the creation of the string array was succesful we continue and the first for loop transfers the command line to the array of strings.

The second for loop just displays the strings.

Note that I use the delete operator to free the memory that was allocated by new. Get into the habit of doing this.

Exercise 3 - Command line arguments

#include <iostream>
#include <iomanip>
#include <string>

void help(void);

main(int argc, char *argv[])
{ int i, sw;
  string *cmdline;

  cmdline = new string[argc];
  if (cmdline != NULL)
   { for (i = 0; i < argc; i++)
      cmdline[i] = argv[i];

     for (i = 0; i < argc; i++)
      { sw = cmdline[i].find("--",0);
        if (sw != string::npos)
         { sw = cmdline[i].find("help", sw + 1);
           if (sw != string::npos)
            { help();
              break;
            }
         }
      }

     delete[] cmdline;
     return 0;
   }
  else
   { cerr << "ERROR: no space."
          << endl;
     return -1;
   }
}

void help(void)
{ cout << "This is the help."
       << endl;
}



There is really nothing new here. It is the previous example and uses the string class find method to first locate '--' and if found then locate 'help'.

Page : 1