Standard Library
class File
An open file.
since 0.1.0-alpha.1linux
- bases
IDisposable
Overview
File(path, mode) opens the file straight away and throws FileException if that fails. Read and write with readln, read, write and writeln, or through the stream views reader() and writer(). A File is IDisposable, so using File f = File(path, mode); closes it for you however the block ends; do not also call close() on such a file.
readln returns "" at the end of the file, which is also what an empty line gives, so a loop that reads until "" stops at the first empty line. The size and modification time are read from the file's path, so they describe the file as it is on disk.
Description
File(path, mode) opens a file when it is constructed, and the open file is the object. If the
file cannot be opened, the constructor throws a FileException, whose message reads
cannot open: <path>.
Modes. The mode is an OpenMode, not an integer, so a wrong value cannot be passed. The
modes are the constants std::read, std::write, std::append and std::binary, and they are
combined with |:
std::readopens an existing file for reading.std::writeopens for writing and starts the file empty.std::appendopens for writing and adds to the end.std::binaryis accepted but has no effect yet; files are read and written as text.
OpenMode has a has(other) method that tells you whether a mode contains a flag. The four
constants are const, so std::read = std::OpenMode(9); is a compile error.
Reading and writing.
write(text)writes text, andwriteln(text)writes it followed by a newline.readln()reads the next line without its newline, and returns""at the end of the file. A blank line is also"", so the two cannot be told apart.read(max)reads up tomaxbytes of text.writer()returns aFileOutStream, whose<<writes strings and chains;reader()returns aFileInStream, whosepull()reads the next line and whoseread(max)reads bytes.
Opening and closing. isOpen() says whether the file is open. close() closes it, and throws
a FileException (not open: <path>) if it is already closed. open() reopens a closed file, and
throws if it is already open.
Information. exists(), size() and modified() describe the file's path. The same queries
are available without opening anything as std::fileExists(path), std::fileSize(path),
std::fileModified(path) and std::isDir(path). For a path that does not exist, fileSize and
fileModified return -1, and fileExists and isDir return false.
File implements IDisposable, so the idiomatic way to use it is a using declaration: the file
is closed on every way out of the block, including a throw.
Missing files and open modes
string missing = "/no/such/directory/data.txt";
console.writeln(std::fileExists(missing));
console.writeln(std::fileSize(missing));
console.writeln(std::isDir(missing));
try {
File f = File(missing, std::read);
console.writeln("opened");
} catch (FileException e) {
console.writeln("caught: ${e.message}");
}
OpenMode readWrite = std::read | std::write;
console.writeln(readWrite.has(std::read));
console.writeln(readWrite.has(std::write));
console.writeln(readWrite.has(std::append));
false
-1
false
caught: cannot open: /no/such/directory/data.txt
true
true
false
Rules
- Opening can throw
FileException; closing an already-closed file does too. - Use
using File f = File(path, mode);so the file is closed even when something throws. writetruncates; useappendto keep what is there.readln()andFileInStream.pull()return""at the end of input, which is the same as a blank line.- Files are text only. Locking, binary access and seeking are not implemented.
- File operations are not available when building for the browser target.
Examples
Writing a file and reading it back. The using declarations close each file at the end of the
function:
string path = "notes.txt";
void save() {
using File out = File(path, std::write);
out.writeln("first line");
out.write("second");
out.writer() << " line" << "\n";
}
void load() {
using File f = File(path, std::read);
console.writeln(f.readln());
console.writeln(f.readln());
console.writeln("size: ${f.size()}");
}
save();
load();
This prints first line, second line and size: 23.
Notes
To process a CSV file, see std.csv, which reads rows from text such as a file's contents.
Examples
Writing and reading a file
void save() {
using File out = File("notes.txt", std::write);
out.writeln("first line");
out.write("second line\n");
}
void load() {
using File src = File("notes.txt", std::read);
string line = src.readln();
while (line != "") {
console.writeln(line);
line = src.readln();
}
}
save();
load();
Handling a file that cannot be opened
try {
File f = File("/no/such/file.txt", std::read);
console.writeln(f.size());
} catch (FileException e) {
console.writeln(e.message);
}
Constructors
new
new(string p, OpenMode m)Opens a file.
Parameters
- p
- The path of the file.
- m
- How to open it; see
OpenMode.
Throws
FileException- when the file cannot be opened, for example because it does not exist when opened for reading only.
Fields
mode
OpenMode modeThe mode the file was opened with.
path
string pathThe path the file was opened with.
Methods
close
close() -> voidCloses the file.
Do not call it on a file that a using declaration owns: the declaration closes the file again when its block ends, and that second close throws.
Throws
FileException- when the file is not open.
See also: IDisposable
exists
exists() -> boolTells whether the file's path exists on disk.
Returns
true when something exists at the path.
See also: fileExists
isOpen
isOpen() -> boolTells whether the file is open.
Returns
true between a successful open and close.
modified
modified() -> intReturns the time the file was last changed, in seconds since 1 January 1970.
Returns
The modification time, or -1 when the path does not exist.
See also: fileModified
open
open() -> voidOpens the file again after it was closed with close.
The file is already open after construction, so you only need this after close.
Throws
FileException- when the file is already open, or cannot be opened.
read
read(int max) -> stringReads up to a number of bytes as text.
Parameters
- max
- The most bytes to read.
Returns
The text read; "" at the end of the file.
read(Block b, int max) -> intReads up to a number of bytes into a Block, starting at its first byte.
Parameters
- b
- The block to fill.
- max
- The most bytes to read.
Returns
The number of bytes read; 0 at the end of the file.
See also: Block
reader
reader() -> FileInStreamReturns a stream that reads from this file.
Returns
A FileInStream on the file's descriptor.
See also: FileInStream
readln
readln() -> stringReads one line, without its line ending.
Returns
The next line, or "" at the end of the file. An empty line in the file also gives "".
size
size() -> intReturns the size in bytes of the file at the path.
Returns
The size in bytes, or -1 when the path does not exist.
See also: fileSize
write
write(string s) -> voidWrites text to the file, exactly as given.
Parameters
- s
- The text to write; no line ending is added.
write(Block b, int off, int len) -> voidWrites part of a Block to the file.
Parameters
- b
- The block to write from.
- off
- The index of the first byte to write.
- len
- The number of bytes to write.
Throws
RuntimeException- when the range
offtooff + lendoes not lie inside the block.
writeln
writeln(string s) -> voidWrites text followed by a newline.
Parameters
- s
- The text to write.
See also: write
writer
writer() -> FileOutStreamReturns a stream that writes to this file, to use with <<.
Returns
A FileOutStream on the file's descriptor.
See also: FileOutStream
See also
- OpenMode — A set of flags that says how a file is opened.
- FileException — The error thrown when a file operation fails.
- IDisposable — The interface of an object that must be cleaned up when its work is finished.
- csv — Read and write CSV (comma-separated values) text.
- FileInStream — A stream that reads text from a file descriptor.
- FileOutStream — A stream that writes text to a file descriptor.
- fileExists — Tells whether a file or directory exists at a path, without opening it.
- isDir — Tells whether a path is a directory.