Reading a Text File into an Array

Rexx provides a Stream method, named MAKEARRAY, that reads the contents of a stream into an array object. MAKEARRAY is convenient when you need to read an entire file into memory for processing. You can read the entire file with a single Rexx clause--no looping is necessary.

The following example (CVIEW.CMD) uses the MAKEARRAY method to read the entire CONFIG.SYS file into an array object. CVIEW displays selected lines from CONFIG.SYS. A search argument can be specified when starting CVIEW:

rexx cview libpath

CVIEW prompts for a search argument if you do not specify one.

If CVIEW finds the string, it displays the line on which the string is found. CVIEW continues to prompt for new search strings until you enter Q in response to the prompt.

/* CVIEW - display lines from CONFIG.SYS                               */
parse upper arg search_string      /* Get any command line argument  */
file=.stream~new("c:\config.sys")  /* Create stream object */
lines=file~makearray(line)         /* Read file into an array object */
                                   /* LINES points to the array obj. */
do forever
   if search_string="" then do     /* Prompt for user input          */
      say "Enter a search string or Q to quit:"
      parse upper pull search_string
      if search_string="Q" then exit
   end  /* Do */
   do i over lines                  /* Scan the array                */
      if pos(search_string,translate(i))>0 then do
         say i                      /* Display any line that matches */
         say "="~copies(20)
      end  /* Do */
   end /* do */
   search_string=""                 /* Reset for next search         */
end /* do */