Quirrel4.41.0

io.file.close

Method of file, from module "io"
instance.close()

Closes the file if it is still open

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

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

try { save.tell() } catch (e) { println("save.tell() after close throws:", e) }

remove(path)
Output:
save.tell() after close throws: the stream is invalid

Errors

Calling close itself never throws, even a second time on an already closed file: it is the other methods that react to the closed state, by throwing the stream is invalid.

Notes

close only has an effect on a file this instance owns. The userpointer constructor form can share a handle without owning it (this is how io.stdout, io.stdin and io.stderr wrap the process's own streams), and on such an instance close does nothing: the handle stays open and every method keeps working.

Example

examples/io/file/close.nut
from "io" import file
from "system" import getenv, remove

let path = $"{getenv("TEMP") ?? getenv("TMP") ?? "/tmp"}/qrl_io_file_close.tmp"
let f = file(path, "w")
f.close()
f.close()                  // closing twice is harmless

try { f.tell(); }
catch (e) { println(e); }  // any other method now sees an invalid stream

remove(path)
Output:
the stream is invalid

See also

constructorTwo 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
flushFlushes the stream and returns non-null on success
stdoutThe process's standard output stream, already open as an io.file instance.
fileclass index