5.9. Reading and Writing

Four built-in functions provide line- and character-oriented
stream reading and writing capabilities: CHARIN(), CHAROUT(),
LINEIN(), LINEOUT().

[CHARIN()]
     is a built-in function that takes up to three parameters,
     which are all optional: the name of the stream to read from,
     the start point, and the number of characters to read. The
     stream name defaults to the default input stream, the start
     point defaults to the current read position, the number of
     characters to read defaults to one character. Leave out the
     second parameter in order to avoid all repositioning. During
     execution, data is read from the stream specified, and
     returned as the return value.

[LINEIN()]
     is a built-in function that takes three parameters too, and
     they are equivalent to the parameters of CHARIN(). However,
     if the second parameter is specified, it refer to a line
     position, rather than a character position; it refers to the
     character position of the first character of that line.
     Further, the third parameter can only be 0 or 1, and refers
     to the number of lines to read; i.e. you cannot read more
     than one line in each call.  The line read is returned by the
     function, or the nullstring if no reading was requested.

[LINEOUT()]
     is a built-in function that takes three parameters too, the
     first is the name of the stream to write to, and defaults to
     the default output stream. The second parameter is the data
     to be written to the file, and if not specified, no writing
     occurs. The third parameter is a line-oriented position in
     the file; if the third parameter is specified, the current
     position is repositioned at before the data (if any) is
     written. If data is written, an end-of-line character
     sequence is appended to the output stream.

[CHAROUT()]
     is a built-in function that is used to write characters to a
     file.  It is identical to LINEOUT(), except that the third
     parameter refers to a character position, instead of a line
     position.  The second difference is that an end-of-line
     character sequence is not appended at the end of the data
     written.

Example: Counting lines, words, and characters

The following REXX program emulates the core functionality of the
wc program under Unix. It counts the number of lines, words, and
characters in a file given as the first argument.

     file = arg(1)
     parse value 0 0 0 with lines words chars
     do while lines(file)>0
          line = linein(file)
          lines = lines + 1
          words = words + words(line)
          chars = chars + length(line)
     end
     say ‘lines=’lines ‘words=’words ‘chars=’chars

There are some problems. For instance, the end-of-line characters
are not counted, and a last improperly terminated line is not
counted either.




PREV NEXT