Reading Binary Files

For our purposes, a binary file is any file whose data is not organized into lines by new-line characters. In most cases, you'll use the character I/O methods (such as CHARS, CHARIN, CHAROUT) on these files. There is one exception, however, which will also be discussed.

Let's start by reading an entire binary file into a single REXX variable. Suppose, for example, that you feel compelled to read the data in the DOINK.WAV file (supplied with OS/2 multimedia support in c:\mmos2\sounds) into a variable. Here's how to do it:

/* GETDOINK -- reads DOINK.WAV into a variable          */
doinkf=.stream~new('c:\mmos2\sounds\doink.wav')
say 'Number of characters in the file=' doinkf~chars

/* Read the whole WAV file into a single REXX variable. */
/* REXX variables are limited by available memory.      */
mydoink=doinkf~charin(1,doinkf~chars)
say 'Number of characters read into variable' mydoink~length

The CHARIN method returns a string of characters from the stream, which in this case is DOINK.WAV. CHARIN accepts two optional arguments. When no arguments are specified, CHARIN reads one character from the current read position and then advances the read pointer.

The first argument is a start position for reading the file. We specified 1 so that CHARIN would begin reading with the first character of the file. We could have omitted the first argument to get the same result.

The second argument tells how many characters to read. We want to read all the characters, so we specified doinkf~chars as the second argument. The CHARS method returns the number of characters remaining to be read in the input stream receiving the message. CHARIN then returns all the characters in the stream. DOINK.WAV has about 7500 characters.


[Back: Writing a Text File]
[Next: Reading Text Files a Character at a Time]