When you execute a program at the command prompt, you type the identification of the program and then press return. You can specify parameters (sometimes called arguments) for the program after the program identification. These can then be accessed by the program to modify its activities.
Hitherto, the identifications of books have always been written
into the actual code. In the last exercise, the input book was called
inbook
and the output book outbook
. If your
program could be given the identifications of the books whenever you
executed the program, then it could have a much wider
applicability.
The command line is available to the program via the channel arg channel. Here is a small program which reads its first argument and prints it on the screen:
PROGRAM arg1 CONTEXT VOID USE standard IF FILE args; open(args,"",arg channel)/=0 THEN put(stand error, ("Cannot access the command line", newline)); stop ELSE on logical file end(arg, (REF FILE f)BOOL: (put(stand error, ("No parameters",newline)); FALSE)); STRING id; get(arg,id); write((id,newline)) FI FINISH
Some points to note:
stand error
is an output FILE
which is usually used
for error messages.
open
is ignored
by arg channel. In the example, it is written as
the empty string.
exit(0)
.
You can only read via the arg channel
(using get). make
term has already been set to make the string
terminator blank (the last argument is
always followed by a space) so you can read the individual parameters
from the command line by reading strings. However, you should note
that when you have read a string, the next character will be the
terminator of the string. So when you have read a string, you will
need to skip all characters which could possibly terminate the reading
of a string (known as terminators) otherwise the
next read of a string will yield the null string
(denoted by ""
). The procedure skip
terminators with header
PROC skip terminators=(REF FILE f)VOID:
is used for this purpose.
ex9.5
(see 9.4) to
get the identifiers of its input and output books from the command
line (remember that the first argument is always the program id, so
use a LOC STRING
for it). Remember to cater for the end of
the input file. AnsSian Mountbatten 2012-01-19