[ 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:
switches, such as -verbose
or -t
parameters (typically filespecs), or simple strings not associated with switches
switched parameters such as the gnu compiler's optional -o
switch, which requires an accompanying parameter, the name of the executable file to generate
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) { if (strcmp(argv[i], "-v")==0) { verbose = true; } if (strcmp(argv[i], "-t") ==0) { test = true; } } for (int i=1; i < argc; ++i) { if (argv[i][0] != '-') processFile(argv[i]); } } [ . . . . ]
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.
Generated: 2012-03-02 | © 2012 Alan Ezust and Paul Ezust. |