File Utilities

The file utilities object ($core.utility.file) along with the file IO prototype object ($core.file_io_proto) define verbs that manipulate files. Children of the file IO prototype object represent open files. File objects are garbage collected (and automatically closed) when no longer used (in other words, you don't have to explicitly worry about management and there's no chance of file handle leakage). A representative use case looks like this:

f = $core.utility.file:open("foobar.txt", "r"); /* open for reading */
while ((line = f:readline()) != ".")
  ...
endwhile

Note the lack of an explicit operation to close the file.

See File IO Prototype for details on the file IO prototype.

open

file $core.utility.file:open(STR path[, STR flags])

Attempts to open the specified file. The path argument is required. The flags argument can include the following:

"r" open the file for reading and fail if the file does not exist
"r+" open the file for reading and writing and fail if the file does not exist
"w" open the file for writing, truncating if it exists and creating if not
"w+" open the file for reading and writing, truncating if it exists and creating if not
"a" open the file for writing, create it if it does not exist; position at the end of the file
"a+" open the file for reading and writing, create it if does not exist; position at the end of the file

The following flags are optional and can be used along with the flags above:

"b" open the file in binary mode
"t" open the file in text mode (default)
"f" force flush data to disk after every write
"n" do not force flush (default)

In text mode, data is written as-is from the MOO, and data read in by the MOO is stripped of unprintable characters. In binary mode, data is converted from MOO binary string format when written and to MOO binary string format when read. In text mode writing, "~1B" means three bytes are written to the file. Similarly, in text mode reading, the line "~1B" means the characters "~", "1" and "B" were present in the file. In binary mode reading, "~1B" means an ASCII ESC character was in the file. In text mode, reading an ESC character from a file results in the ESC getting stripped.

Examples:

$core.utility.file:open("foobar.txt", "r")     => file /* file is opened for reading in text mode */
$core.utility.file:open("foobar.png", "wb")    => file /* file is opened for writing in binary mode */