Reading a Text File into an Array

Rexx provides a Stream method, named ARRAYIN, that reads the contents of a stream into an array object. ARRAYIN 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.rex) uses the ARRAYIN method to read the entire log.txt file into an array object. cview&per;cmd displays selected lines from log.txt. A search argument can be specified when starting cview&per;cmd:

rexx cview libpath

cview&per;cmd prompts for a search argument if you do not specify one.

If cview&per;cmd finds the string, it displays the line(s) in which the string was found. cview&per;cmd continues to prompt for a new search string until you enter Q in response to the prompt.


cview&per;cmd
/* cview&per;cmd - display lines from file log.txt */
parse upper arg search_string /* Get any command line argument */
file=.stream~new("log.txt") /* Create stream object */
lines=file~arrayin /* Read file into an array object */
/* LINES points to the array obj. */
loop 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
loop 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
end
search_string="" /* Reset for next search */
end