Many programs that you run from a DOS prompt allow you to specify extra information that the programs can use. This short page illustrates how you could get filenames the way copy and del do.
Other programs which allow the user to specify data used by the program have been termed interactive: they prompt the user for information and then proceed to use it. An example of this is the interactive triangle-area program, which uses the write/readln combination to get information.This raises two issues: How does a program obtain information from the Command Line? How does the user know how to use the program?
Sample code of a program which combines both methods of getting information from the user is provided.
The mechanism for accessing the arguments is quite simple. Consider the following Command Line which could be used to get the program copyfile to read a text file called orig.txt and create a copy called copy.txt.
convtxt orig.txt copy.txt
Two built-in functions will be utilized:
Since the user receives no explicit prompts, the program must make decisions given the information provided from the command line. Consider the following if structure:
{Get SRC and DEST file names}
if ParamCount = 2 then
begin
{Get from the Command Line}
InName := ParamStr(1);
OutName := ParamStr(2)
end
else
begin
{Inform user of correct usage and ask for file names}
writeln('Usage: ', ParamStr(0), sourcefile destinationfile');
write ('What is the source file? ');
readln(InName);
write ('What is the destination file? ');
readln(OutName)
end;
If the program name is followed by two parameters, the parameters are assigned to the string variables InName and OutName. Otherwise, the user is informed of Command-Line Usage and is then prompted for the file names.
Back to Top
The following complete program demonstrates how to access and process the command line information. The purpose of the program is to create a copy of a file. N.B. There is no bulletproofing included for a nonexistent source file.
Program CopyFile;
{ Copy a file }
{ Usage: copyfile sourcefile destinationfile
OR: copyfile }
var
NextCh : char;
Infile, Outfile: file of char;
InName, OutName: string;
begin
{Get SRC and DEST file names}
if ParamCount = 2 then
begin
{Get from the Command Line}
InName := ParamStr(1);
OutName := ParamStr(2)
end
else
begin
{Inform user of correct usage and ask for file names}
writeln('Usage: ', ParamStr(0), sourcefile destinationfile');
write ('What is the source file? ');
readln(InName);
write ('What is the destination file? ');
readln(OutName)
end;
{Open files for access}
assign(Infile, InName);
assign(Outfile, OutName);
reset(Infile);
rewrite(Outfile);
{Convert file}
while not EOF(Infile) do
begin
read(Infile, NextCh);
write(Outfile, NextCh)
end;
{Close files}
close(Infile);
close(Outfile);
write(ParamStr(0), ' has successfully copied ');
writeln('file ', Inname, ' to file ', Outname, '.')
end.