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.

Handling the different kinds of command line arguments can be done in a variety of ways. Suppose that you are writing 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 appears. In usage descriptions, optional arguments are always enclosed in [square brackets] while 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.23 shows how a C program might deal with command line arguments:

Example 6.23. src/reuse/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

In Qt, we wish to avoid the use of arrays, pointers, and <cstring> in favor of more object-oriented constructs.

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