File class for Nand2Tetris Virtual Machine Emulator

class File
Constructor
File new()
Destructor
void dispose()
Methods
boolean open(String name, boolean write)
boolean openDir(String name)
void close()
boolean eof()
void rewind()
char readByte()
int readInt()
char readChar()
String readString(int length)
boolean writeByte(char c)
boolean writeInt(int i)
boolean writeChar(char c)
boolean writeString(String str)
boolean writeln()
int lastError()
Functions
void init()
boolean exists(String name)
boolean isFile(String name)
boolean isDir(String name)
int version()
String getVMEFSROOT()
String getMountPoint()

Class File allows programs running in the VMEmulator to read and write data on the host computer's disk.

Access to the host computer's disk is limited to files in or below a directory on the host's file system that is the VME's mount point.

By default, the mount point is nand2tetris/tools/VmeFileSystem, assuming VMEmulator is installed in nand2tetris/tools. The mount point can be overridden with the VMEFSROOT environment variable.

Possible uses for Jack programs to read and write files on the host might be for a game to save high score information, or for the very ambitious, rewrite the Assembler, VM translator and Jack compiler in Jack and run them on the VM emulator.

Example usage — copying a file

function void copyFile(String src, String dest) {
    var File fin, fout;
    var char c;

    let fin = File.new();
    if (fin.open(src, false)) {
        let fout = File.new();
        if (fout.open(dest, true)) {
            while ( ~ fin.eof()) {
                let c = fin.readByte();
                do fout.writeByte(c);
            }
        }
        do fout.close();
        do fout.dispose();
    }
    do fin.close();
    do fin.dispose();
    return;
}

Function Reference

function void init()
Initializes the File class.
Parameters
none
Return value
none
Errors
none
File.init() should be called at the beginning of Main.main(), before any other File functions are called.

A limitation of built-in VM classes is that there is no "on reset" call. This means that any host resources that are in use when the VM resets are not closed or released. init() closes any host files that were left open on the host so that reset...run will work correctly.

constructor File new()
Allocates a new File object.
Parameters
none
Return value
A newly allocated File object.
Errors
none
method void dispose()
Deallocates this File object.
Parameters
none
Return value
A newly allocated File object.
Errors
none
dispose() may be called while a file is still open. The file will be correctly closed before the File object is deallocated.
method int lastError()
Returns the last error that occurred on this File object.
Parameters
none
Return value
Error Value Cause
  0No error.
ROOT_MKDIR_FAILED100The mount point directory does not exist and cannot be created.
ROOT_NOT_A_DIR101The mount point is not a directory.
ILLEGAL_NAME102Illegal file name.
OPEN_FAIL103Host computer open() failed.
DIRECTORY104Tried to open() a directory [need to use openDir()].
WRONG_MODE105File is open in the wrong mode for a read or write operation.
END_OF_FILE106End-of-file on read.
IO_ERROR107Host computer reports I/O error.
STRING_OVERFLOW 17ReadString() returned a partial line.
method boolean exists(String name)
method boolean isFile(String name)
method boolean isDir(String name)
Test if a file exists, is a normal file, or is a directory.
Parameters
namethe file name to be tested.
Return value
true if the name is a directory
Errors
ROOT_MKDIR_FAILED, ROOT_NOT_A_DIR

I/O functions

method boolean open(String name, boolean write)
Opens a file for reading or writing.
Parameters
namethe name of the file to be opened.
writetrue if the file should be opened/created for writing.
Return value
true if the file was opened, false if an error occurred.
Errors
ROOT_MKDIR_FAILED, ROOT_NOT_A_DIR, WRONG_MODE, ILLEGAL_NAME, DIRECTORY, OPEN_FAIL
If a file being opened for write already exists, it will be truncated to 0 length before new data is written. Subdirectories in name will be created if they don't exist. If they cannot be created, open() will fail.
method boolean openDir(String name)
Opens a directory for reading.
Parameters
namethe name of the directory to be opened.
Return value
true if the directory was opened, false if an error occurred.
Errors
ROOT_MKDIR_FAILED, ROOT_NOT_A_DIR, WRONG_MODE, ILLEGAL_NAME, OPEN_FAIL
The directory is read as if it were a text file with one name per line. Only ReadString(), eof() and close() are supported for directories.
method void close()
Closes the file.
Parameters
none
Return value
none
Errors
none
You don't need to close() before dispose()...

It's OK to close() even if you didn't open()...

method boolean eof()
Tests end-of-file / end-of-directory status.
Parameters
none
Return value
true if all data has been read from the file or directory,
undefined for files opened for write.
Errors
WRONG_MODE, IO_ERROR
eof() is strictly not required because the read routines all handle EOF in a detectable manner, but it solves many code structure problems since Jack doesn't support "break" statements.
method void rewind()
Seek back to the beginning of a file opened for read.
Parameters
none
Return value
none
Errors
WRONG_MODE, IO_ERROR
rewind() is useful when more than one pass is required to process the data in a file.
method char readByte()
Reads an 8-bit unsigned integer from the file.
Parameters
none
Return value
A Hack character with the byte in the lower 8 bits, or -1 on EOF or error.
Errors
WRONG_MODE, IO_ERROR
See Also
readChar() to read an 8-bit character.
method int readInt()
Read a 16-bit integer from the file. The integer is read MSB, LSB.
Parameters
none
Return value
Integer read from file, or -1 on EOF or error.
Errors
WRONG_MODE, IO_ERROR
There is no EOF or error information in the return value from readInt(). Therefore, you must use eof() or lastError() to detect abnormal conditions.
method char readChar()
Reads an 8-bit character from the file.
Parameters
none
Return value
A Hack character with the 8-bit character in the lower 8 bits, or -1 on EOF or error.
Errors
WRONG_MODE, IO_ERROR
See Also
readByte() to read an 8-bit unsigned integer.
readChar() handles both Windows and Linux / Mac new-line sequences by discarding \r characters and translating \n characters to NEWLINE_KEY (128).
method String readString(int length)
Read the next line from the file or directory and return it in a new String.
Parameters
lengthmaximum length for the new String.
Return value
The next line in the file, with the new-line character(s) removed, or
the first length characters of a longer line, with lastError() set to STRING_OVERFLOW (17), or
NULL (0) with lastError() set to an error code.
Errors
WRONG_MODE, IO_ERROR,
readString() handles both Windows and Linux / Mac new-line sequences by discarding \r characters and triggering on \n characters.
method boolean writeByte(char c)
Writes an 8-bit unsigned integer to the file.
Parameters
cthe data to be written.
Return value
true if the write succeeded.
Errors
WRONG_MODE, IO_ERROR
See Also
writeChar() to write an 8-bit character.
method boolean writeInt(int i)
Writes a 16-bit integer to the file. The integer is written MSB, LSB.
Parameters
ithe data to be written.
Return value
true if the write succeeded.
Errors
WRONG_MODE, IO_ERROR
method boolean writeChar(char c)
Writes an 8-bit character to the file.
Parameters
cthe character to be written.
Return value
true if the write succeeded.
Errors
WRONG_MODE, IO_ERROR
See Also
writeByte() to write an 8-bit unsigned integer.
The upper 8 bits of Hack characters are discarded.
A NEWLINE_KEY character will be translated to a host new-line (\n or \r\n).
method boolean writeString(String str)
Writes a String to the file.
Parameters
strthe data to be written.
Return value
true if the write succeeded.
Errors
WRONG_MODE, IO_ERROR
A new-line is not written after the String. See writeln().
Any NEWLINE_KEY characters in the string will be translated to host new-lines (\n or \r\n).
method boolean writeln()
Writes a host new-line (\n or \r\n) to the file.
Parameters
none
Return value
true if the write succeeded.
Errors
WRONG_MODE, IO_ERROR
method void init()
Initializes the File class.
Parameters
none
Return value
none
Errors
none

Auxiliary functions

function int version()
Get the File.class version number.
Parameters
none
Return value
An integer in the form xxyy where xx is the major version and yy is the minor version (as in xx.yy)
Errors
ROOT_MKDIR_FAILED, ROOT_NOT_A_DIR
Current version is 1.01. The major version will be incremented if new functionality is added to File.class. The minor number will be updated for bug fixes.
function String getVMEFSROOT()
function String getMountPoint()
Return the environment variable and the file system mount point.
Parameters
none
Return value
A new String set to the value.
Errors
ROOT_MKDIR_FAILED, ROOT_NOT_A_DIR
These functions can be used to debug mount point problems.

Setting the VMEFSROOT Environment Variable

The easiest way to set the VMEFSROOT variable is by editing the script or batch file that you are using to start the VM emulator and adding this command to beginning of the file.
Windowsset VMEFSROOT=C:\some\directory
Unix/Linuxexport VMEFSROOT=/some/directory
Always set VMEFSROOT to an absolute path.