Quirrel4.41.0

io.file.constructor

Method of file, from module "io"
constructor(path: string|userpointer, mode: string|int|null): instance

Two forms: (path: string, mode: string) opens the file via fopen with the given mode; (handle: userpointer, own) wraps an existing FILE* and takes ownership (closes on destruction) when own is non-null, or shares it without closing when own is null

examples/io/file/constructor-basic.nut
from "io" import file
from "system" import getenv, remove

let path = $"{getenv("TEMP") ?? getenv("TMP") ?? "/tmp"}/qrl_io_file_constructor_basic.tmp"
let save = file(path, "w")
println("typeof save =", typeof save)

save.close()
remove(path)
Output:
typeof save = file

Parameters

pathstring|userpointerthe file to open, or the userpointer handle to wrap
modestring|int|nullan fopen mode string for the first form; for the second form, ownership of the handle (non-null closes it on destruction, null shares it)

Errors

Throws invalid file mode when mode is not one of the accepted strings, checked before path is touched. Throws cannot open file when the mode is fine but the underlying fopen fails, for example because path does not exist or its directory does not.

Notes

mode must be r, w or a, optionally followed by +, b or t in either order (r+, rb, r+b, rb+, rt+, and so on) - the same set fopen accepts. b and t only matter on a platform where the C library translates line endings in text mode: opening with w (no b) and writing "\n" can land 2 bytes on disk, not 1, while wb writes exactly what was asked. Prefer a b mode whenever the byte count has to be exact, which writestring, writen and writeblob all promise.

A file does not have to be closed by hand for its data to survive: the instance is reference-counted, so dropping the last reference destroys it immediately, which flushes and closes the handle the same as calling close. Only a reference cycle defers that to the next run of collectgarbage.

Example

examples/io/file/constructor.nut
from "io" import file

let path = "definitely/does/not/exist.bin"

try { file(path, "zz"); }        // mode is checked before the path is ever touched
catch (e) { println("file(path, \"zz\") throws:", e); }

try { file(path, "r"); }         // mode is fine now, but the path still is not there
catch (e) { println("file(path, \"r\") throws:", e); }
Output:
file(path, "zz") throws: invalid file mode
file(path, "r") throws: cannot open file

See also

closeCloses the file if it is still open
stdoutThe process's standard output stream, already open as an io.file instance.
removeDeletes the file at the given path, throws error in case of fail
fileclass index