REBOL 3 Docs Guide Concepts Functions Datatypes Errors
  TOC < Back Next >   Updated: 6-Feb-2009 Edit History  

REBOL 3 Concepts: Ports: Other Port Modes

Pending Revision

This document was written for R2 and has yet to be revised for R3.

Contents

Line Mode

The open function allows ports to be opened for line access. In line mode, the first function will return a line of text, rather than a character. The example below reads a file one line at a time:

fp: open/lines %file.txt
print first fp
I wanted the gold, and I got it --
print third fp
Yet somehow life's not what I thought it,

The /lines refinement is also useful for Internet protocols that are line oriented.

tp: open/lines tcp://server:8000
print first tp

Read and Write Only

You can use the /read refinement to open a port as read only:

fp: open/read %file.txt

Changes made to the port's buffer, are not written back to the file.

To open for write only, use the /write refinement:

fp: open/write %file.txt

File ports opened with the /write refinement will not read the current data upon opening the port.

Closing, or updating a write only file port will cause existing data in the file to be overwritten:

insert fp "This is the law of the Yukon..."
close fp
print read %file.txt
This is the law of the Yukon...

Direct Port Access

The /direct refinement opens an unbuffered port. This is useful to access files a portion at a time, such as when a file is too large to be held in memory.

fp: open/direct %file.txt

Reading the data with a copy function will move the port's head forward:

print copy/part fp 40
I wanted the gold, and I sought it,^/ I
print copy/part fp 40
scrabbled and mucked like a slave.^/Was i

In direct mode, the port will always be at its head position:

print head? fp
true

The copy function will return none! when the port has reached its end.

Here is an example that uses direct ports to copy a file of any size:

from-port: open/direct %a-file.jpg
to-port: open/direct %a-file.jpg
while [data: copy/part from-port 100000 ][
    append to-port data
]
close from-port
close to-port

Skipping Data

There are two ways to skip data that exists in a port. First, you can open the port with the /skip refinement. This open function will automatically skip to a point in the port. For example:

fp: open/direct/skip %file.big 1000000

fp: open/skip http://www.example.com/bigfile.dat 100000

You can also use the skip function on the port. For files that are opened with /direct and /binary the skip operation is identical to a file system seek operation. Data is not read into memory. This is not possible in /string mode because the line breaks interfere with the skip size.

fp: open/direct/binary %file.dat
fp: skip fp 100000


  TOC < Back Next > REBOL.com - WIP Wiki Feedback Admin