Class File
The File
class provides a wrapper over a C FILE * struct. A File
is
closed automatically when a scope exits (though not immediately). However,
it is also possible to manually close a File
.
public define close
Close self
if it is open, or do nothing if already closed.
For standard streams, this marks the File
as closed, but does not
actually close the stream. Embedders, therefore, do not need to worry
about standard streams being altered or closed by Lily.
public define each_line(fn: Function(ByteString))
Read each line of text from self
, passing it down to fn
for
processing.
IOError
ifself
is not open for reading, or is closed.
public define flush
This function writes all buffered data associated with the File
provided.
IOError
ifself
is closed or not open for writing.
public static define open(path: String, mode: String): File
Attempt to open path
using the mode
given. mode
may be one of the
following:
"r"
(read only, must exist)
"w"
(write only)
"a"
(append, create if not exist)
"r+"
(read+write, must exist)
"w+"
(read+write, creates an empty file if needed)
"a+"
(read+append)
IOError
if unable to openpath
, or an invalidmode
is provided.
public define print(data: A)
Attempt to write the contents of data
to the file provided. data
is
written with a newline at the end.
IOError
ifself
is closed or is not open for writing.
public define read(size: *Integer): ByteString
Read size
bytes from self
. If size
is negative, then the full
contents of self
are read. This stops if either size
bytes are read,
or the end of self
is reached.
IOError
ifself
is not open for reading, or is closed.
public define read_line: ByteString
Attempt to read a line of text from self
. Currently, this function
does not have a way to signal that the end of the file has been reached.
For now, callers should check the result against B""
. This will be
fixed in a future release.
IOError
ifself
is not open for reading, or is closed.
public static define read_to_string(path: String): String
Convenience method for reading a whole file into a String
.
This opens the file named path
, reads all content into a String
,
then closes the file.
IOError
if unable to openpath
.
ValueError
if the content read is not valid utf-8.
public define write(data: A)
Attempt to write the contents of data
to the file provided.
- If
self
is closed or is not open for writing,IOError
is raised.
public static define write_to_path(path: String, data: A)
Convenience function for writing data to a file.
This opens the file named path
, writes data
to it, then closes the
file.
IOError
if unable to openpath
.