io.file.close
Closes the file if it is still open
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 invalidErrors
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
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 invalidSee also
constructor | 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 |
flush | Flushes the stream and returns non-null on success |
stdout | The process's standard output stream, already open as an io.file instance. |
| file | class index |