Statement macro
Runs a body of code within the context of a file stream.
with-open-file (stream-var = filename, #rest keys)
body end => values
<string>.
<object>.
<object>.
io
streams
Provides a safe mechanism for working with file streams. The macro creates a file stream and binds it to stream-var, evaluates a body of code within the context of this binding, and then closes the stream. The macro calls close upon exiting body.
The values of the last expression in body are returned.
Any keys are passed to the make method on <file-stream>.
The following expression yields the contents of file foo.text as a <byte-vector>:
with-open-file (fs = "foo.text", element-type: <byte>) read-to-end(fs) end;
It is roughly equivalent to:
begin
let hidden-fs = #f; // In case the user bashes fs variable
block ()
hidden-fs := make(<file-stream>,
locator: "foo.text", element-type: <byte>);
let fs = hidden-fs;
read-to-end(fs);
cleanup
if (hidden-fs) close(hidden-fs) end;
end block;
end;