REBOL Document

Read-io - Function Summary


Low level read from a port.


read-io port buffer length


port - Already opened port to read from. (must be: port)

buffer - Buffer to which to append data. (must be: any-string)

length - Maximum number of chars to read. (must be: number)


This function provides a low level method of reading data from a port. For most code, this function should not be used because the COPY function is the proper method of reading data from a port. However, under some situations, using READ-IO may be necessary.

The primary difference between READ-IO and COPY is that READ-IO requires a fixed size buffer and maximum transfer length as its arguments. Like the READ function of the C language, bytes are transferred into the buffer up to the maximum length specified. The length of the transfer is returned as a result, and it can be zero (for nothing transferred), or even negative in the case of some types of errors.

Here is a simple example of READ-IO on a file <B>(Note again: this is a low level IO method; you should normally use the series functions like COPY, INSERT, NEXT, etc. for reading and writing to IO ports.)</B>

    write %testfile "testing"
    buffer: make string! 100
    port: open/direct %testfile
    read-io port buffer 4
    close port
    probe buffer

If the length of the transfer is larger than the buffer provided, the length will be truncated to the buffer size, just as if that length was provided as the argument (so no data will be lost).

The code below provides an excellent example of READ-IO for reading CGI (web server) data:

    read-cgi: func [
        "Read CGI form data from GET or POST."
        /local data buf
        if system/options/cgi/request-method = "POST" [
            data: make string! 1020
            buffer: make string! 16380
            while [positive? read-io system/ports/input buffer 16380][
                append data buffer
                clear buffer
            return data
        if system/options/cgi/request-method = "GET" [
            return system/options/cgi/query-string
        test-data ; if in test mode

In this example, if the CGI request is a POST type, then data is supplied as a binary stream to REBOL's input port. The code shows how the port is read until all data has been collected (while the return value is positive). Note that the BUFFER is a fixed size and as it is read, data is being accumulated into a self-expanding DATA buffer.


write-io - Low level write to a port.

<Back | Index | Next>

Copyright 2004 REBOL Technologies