6.7.  Processing Command-Line Arguments

[ fromfile: argumentlist.xml id: cmdlineargs ]

Applications that run from the command-line are often controlled through command-line arguments, which can be switches or parameters. ls, g++, and qmake are familiar examples of such applications.

You can handle the different kinds of command-line arguments in a variety of ways. Suppose that you write a program that supports these options:

Usage:
   a.out [-v] [-t] inputfile.ext [additional files]
     If -v is present then verbose  = true;
     If -t is present then testmode = true;

Typically, the program does not care about the order in which these optional switches appear. In usage descriptions, optional arguments are always enclosed in [square brackets] whereas required arguments are not. This program accepts an arbitrarily long list, consisting of at least one file name, and performs the same operation on each file.

In general, command-line arguments can be any of the following:

The following line contains examples of all three kinds of arguments:

  g++ -ansi -pedantic -Wall -o myapp someclass.cpp someclass-demo.cpp
  

Example 6.25 shows how a C program might deal with command-line arguments.

Example 6.25. src/derivation/argumentlist/argproc.cpp

[ . . . . ]
#include <cstring>

bool test = false;
bool verbose = false;

void processFile(char* filename) {
[ . . . . ]
}

/*
  @param argc - the number of arguments
  @param argv - an array of argument strings
*/
int main (int argc, char* argv[]) {
  // recall that argv[0] holds the name of the executable.
  for (int i=1; i < argc; ++i) { 1

     if (strcmp(argv[i], "-v")==0) {
        verbose = true;
     }
     if (strcmp(argv[i], "-t") ==0) {
        test = true;
     }
  }
  for (int i=1; i < argc; ++i) { 2
     if (argv[i][0] != '-') 
        processFile(argv[i]);
  }
}
[ . . . . ]

1

First process the switches.

2

Make a second pass to operate on the non-switched arguments.

<include src="src/derivation/argumentlist/argproc.cpp" href="src/derivation/argumentlist/argproc.cpp" id="ex-argproc" mode="cpp"/>


Qt enables you to avoid the use of arrays, pointers, and <cstring> by using more object-oriented constructs.

In Example 6.26 you can see how code like this could be greatly simplified through the use of higher-level classes, QString and QStringList.