11.1 Command-line arguments

At present, our program only works with one file data1. It would be more useful if the name of the file could be specified by the user. A common way to allow this in UNIX is to pass the name of the files to be used as arguments on the command line used to invoke the program. For example, to count the characters in file data2, we would like to invoke count as follows:

% CountChar data2

The demo file programs that come with BETA all work this way. To do this, there are two useful functions in the standard environment which correspond to the UNIX C argc and argv variables. These are:

Below, we show how count has been modified to use the command argument. To keep things simple, we do not check the number of arguments or provide for an error message. For examples of how to do this, see the demo programs.

Program 13: CountChar1.bet

ORIGIN '~beta/basiclib/file'
---- program: descriptor ----

(# (* ----------------------------------------------
    *   count.bet: Simple file handling program
    *              -Counting characters-
    * ----------------------------------------------*)
   
   inFile: @file;
   Ch: @char;
   nc: @integer;
do
   (if  NoofArguments = 2 then
       2->ARGUMENTS->inFile.name ;
       inFile.openRead;  (* OPENING *)
       
       'Reading: '->puttext;   inFile.name->putline;
       Loop: 
         (if not inFile.eos then
             inFile.get->Ch; 
             nc + 1->nc;
             (if nc mod 10 = 0 then '.'->put  if);
             restart Loop
         if);
       newline;
       nc->putint; ' characters in file'->putline;
       inFile.close;
    else 
       'Missing Arguments'->putline;
   if)
#)

And below we show the application of CountChar1 to the count program itself.

nil% CountChar1 CountChar1.bet
Reading: CountChar1.bet
.......................................................................
681 characters in file
nil%

A nice thing about passing file names as command line arguments is that the shell will expand the file name as expected. In particular, the '~' and '*' characters are interpreted correctly in the example below [2]:

nil% count ~/Beta/dat*
Reading: ../Beta/data1
....
41 characters in file

These also work:

Were we to set the filename directly, it would be OK to include '.' and '..' in the path name but '~' would not be handled properly.


[2] For Unix shells only


Libraries Tutorial
© 1994-2004 Mjølner Informatics
[Modified: Thursday January 16th 2003 at 10:23]