/ lang / read
READ
Syntax

    READ [ # Stream , ] Variable [ , Length ]
    READ [ # Pointer , ] Variable [ , Length ]

Reads the stream Stream as binary data whose type is given by the type of the variable. The binary representation is the one used by the WRITE instruction.

If the stream is not specified, then the standard input is used.

If Variable is a string, you can specify a length that indicates the number of bytes to read. If the length is negative, then (- Length) bytes are read up to the end of stream.

If no length is specified for a string, or if Length is zero, then the string length is read from the stream. The string then must have been written with the WRITE instruction.

| This instruction uses the byte order of the stream to read the data.

If you specify a Pointer instead of a Stream, then data will be read directly from the memory address specified by the pointer.

| If you try to read at a forbidden memory address, you will get an error. The interpreter won't crash.

This example demonstrates how to read a binary file. It will prompt the user to open a wav music file in order to display information from the wav header. It OPEN's the file and then uses SEEK to locate the start of the wav file header. Then we use READ to get the wav header information. Note that we need to read the right number of bytes for each variable. Hence some of the data types we read are Short and some are Integer. Finally we simple display the information.

### Examples

    PUBLIC Type AS Short
    PUBLIC Channels AS Short
    PUBLIC SampleRate AS Integer     ' Hz
    PUBLIC BytesPerSecond AS Integer ' Bytes
    PUBLIC Alignment AS Short
    PUBLIC SampleSize AS Short       ' Bits
    PUBLIC FileSize AS Integer       ' Bytes
    PUBLIC Duration AS Float         ' Seconds

    PUBLIC SUB ButtonRead_Click()
      DIM wav AS File
      Dialog.Filter = ["*.wav", "WAVE music files"]
      IF Dialog.OpenFile() THEN RETURN
      ' We need the file size to calculate the duration
      FileSize = Stat(Dialog.Path).Size
      wav = OPEN Dialog.Path FOR READ
      SEEK #wav, 20 ' The info we want starts 20 bytes into the file
      READ #wav, Type
      READ #wav, Channels
      READ #wav, SampleRate
      READ #wav, BytesPerSecond
      READ #wav, Alignment
      READ #wav, SampleSize
      CLOSE #wav
      ' Calc duration in seconds
      Duration = FileSize / BytesPerSecond
      ' Display results
      PRINT "Type                " & Type
      PRINT "Channels            " & Channels
      PRINT "Sample Rate (Hz)    " & SampleRate
      PRINT "Bytes Per Second    " & BytesPerSecond
      PRINT "Alignment           " & Alignment
      PRINT "Sample Size (Bytes) " & SampleSize
      PRINT "File Size (Bytes)   " & FileSize
      PRINT "Duration (Seconds)  " & Duration
    CATCH
      PRINT Error.Text
    END

### See also

Stream & Input/Output functions Stream.ByteOrder Binary Data Representation External Function Management