Reva: Files & File Handling

Files & File Handling

For details on all the file handling words in Reva, use the help facility:

help file-io

As a simple example, let's create a file which will have "Hello world!" in it:

" hello.txt" creat
dup " Hello world!" rot write

The first line creates the file "hello.txt" in the current directory, if it did not already exist (use {{word|open/rw}} to open an existing file for writing). The return value is the 'handle' of the file, which we immediately {{word|dup}}. The string to write follows, so the stack at this point looks like:

file-handle file-handle address-of-string size-of-string

The word {{word|write}} expects the handle to write to in TOS, so we do {{word|rot}}, and then write out the buffer to file. All that remains is to close the file (this is almost always a good idea, even though the OS will close files on our behalf if we forget).

Verify that you now have a file "hello.txt" with the text indicated.

Note that we did not check for errors. The Reva file-io philosophy is that "it normally works", so make the code easier to read by not having error code checks everywhere. However, you can check for errors by consulting the value held in {{word|ioerr}} after each I/O operation.

Note that a simple way to read in an entire file is via {{word|slurp}}. That word allocates memory for a buffer big enough to hold the file, and returns the contents of that file as a string. This works great for small files, but you don't want to try it on big ones, probably...