File
A file is where a program's data outlives the program. Writing one and reading it back takes only a handful of calls, but every one of them can fail for reasons outside the program: the disk is full, the name is taken, permission is refused, the file is not there. So every step declares throws IoError, every call to one is marked with try, and this lesson accounts for each one.
Main throws too: func Main() throws IoError, as in Fallible main. A plain try anywhere passes an error on, and when one reaches Main the program ends with exit status 1. Turning the text into a path, with OsString::FromText, cannot fail, so it needs no try.
Opening a file
File::Open takes an allocator, a path and an OpenOptions saying what you mean to do:
var writing = try File::Open(allocator, path, OpenOptions::Writing());
The options decide both what the handle may do and what happens to the file itself:
| Options | The handle may | If the file is missing | If it exists |
|---|---|---|---|
OpenOptions::Reading() | read | throws NotFound | opened as it is |
OpenOptions::Writing() | write | created | emptied first |
OpenOptions::Appending() | write at the end | created | kept; writes go after it |
The open file is a File, and it must be var: writing, reading and closing all change it.
Writing, and closing
try WriteAll(writing, "first line\nsecond line\n");
try writing.Close();
File::Write is a single attempt: it may move fewer bytes than asked, and the count it returns says how many. Io::WriteAll keeps calling Write until every byte is out, which is almost always what you want.
Close can throw as well. The system may have delayed reporting a failed write until now, so a close that is not checked can lose an error that happened earlier.
Reading until the end
File::Read fills as much of a buffer as it can in one attempt and returns how many bytes it put there. The lesson's buffer is only eight bytes, so the 23 bytes of the file take several reads:
var buffer: char8[8];
var reads = 0;
var total: uint = 0;
loop {
let filled = try reading.Read(buffer[..8]) catch {
error if error.IsEnd() => break,
error => throw error
};
Print("{}", buffer[..filled]);
reads += 1;
total += filled;
}
The surprise is how the end arrives. It is not a count of zero: it is thrown, as an IoError whose IsEnd() is true. So the read is a try ... catch with two arms, separated by a guard: the end of the file breaks out of the loop, and any other error is a real failure, thrown on with throw error. The arms must cover every IoError, which is why the last one binds them all.
flowchart LR
r["`reading.Read(buffer[..8])`"] --> q{"what came back?"}
q -- "a count" --> use["print `buffer[..filled]`,<br/>add it up, read again"]
use --> r
q -- "a thrown `IoError`,<br/>`IsEnd()` `true`" --> done["break: the file is read"]
q -- "any other<br/>`IoError`" --> fail["`throw error`:<br/>`Main` ends with status `1`"]Only the first filled bytes are new. The rest of the buffer still holds whatever the previous read left there, which is why the loop prints buffer[..filled], never the whole buffer.
| Read | Bytes | Buffer holds |
|---|---|---|
| 1 | 8 | first li |
| 2 | 8 | ne, a newline, secon |
| 3 | 7 | d line and a newline, plus a stale n |
| 4 | — | the end of the file: break |
Handling an error instead of passing it on
Not every error should end the program. After DeleteFile the file is gone, so opening it again must throw — and here that is the expected outcome. A try block covers the statements that use the file, and its catch decides what each error means:
try {
var reopened = File::Open(allocator, path, OpenOptions::Reading());
PrintLine("still there?");
reopened.Close();
} catch {
error if error.kind == IoErrorKind::NotFound => PrintLine("deleted, as expected"),
error => throw error
}
Inside the block, the calls that can throw need no try of their own: the block marks them all. error.kind is an IoErrorKind, an enum that names what went wrong in the same way on every platform: NotFound, PermissionDenied, AlreadyExists, StorageFull and more. The guard picks out the one error this code expects; anything else is still thrown on.
The program
The whole lesson is one package in the Examples repository. Its comments explain every step.
// Writing a text file and reading it back, with every failure accounted for.
//
// Each step can fail for reasons outside the program: the disk is full, the name is taken,
// permission is refused. So each one declares `throws IoError`, every call to one is marked with
// `try`, and `Main` declares `throws IoError` too: plain `try` passes an error on and the program
// ends with exit status 1.
//
// Two surprises are worth knowing before the code.
//
// - `File::Write` and `File::Read` are single attempts. Each may move fewer bytes than asked,
// and the count it returns says how many. `Io::WriteAll` keeps calling `Write` until every
// byte is out, and a reader loops in the same way.
// - The end of a file is not a count of zero. It is thrown, as an `IoError` whose `IsEnd()` is
// true, so the read loop's `catch` treats it as "done" and rethrows any other error.
//
// The file lives in this package's `Bin/` folder, and the program deletes it at the end.
import Allocator::SystemAllocator;
import FileSystem::{ DeleteFile, File, OpenOptions };
import Io::{ IoError, IoErrorKind, Print, PrintLine, WriteAll };
import Path::{ OsString, Path };
func Main() throws IoError {
let allocator = SystemAllocator();
var holder = OsString::FromText(allocator, "Bin/notes.txt");
let path = Path::FromView(holder.View());
// `Writing` creates the file, or empties it if it already exists.
var writing = try File::Open(allocator, path, OpenOptions::Writing());
try WriteAll(writing, "first line\nsecond line\n");
// Closing can report a failure that was delayed until now, so it can throw too.
try writing.Close();
PrintLine("wrote {}", path);
// `Reading` requires the file to exist. A small buffer makes the loop take several reads.
var reading = try File::Open(allocator, path, OpenOptions::Reading());
var buffer: char8[8];
var reads = 0;
var total: uint = 0;
loop {
let filled = try reading.Read(buffer[..8]) catch {
error if error.IsEnd() => break,
error => throw error
};
// Only the first `filled` bytes are new. The rest of the buffer is left over.
Print("{}", buffer[..filled]);
reads += 1;
total += filled;
}
try reading.Close();
PrintLine("read {} bytes in {} reads", total, reads);
try DeleteFile(allocator, path);
// Handling an error instead of passing it on: the file is gone, so opening it throws. A
// guarded arm picks out the expected kind, and any other error is thrown on to the caller.
try {
var reopened = File::Open(allocator, path, OpenOptions::Reading());
PrintLine("still there?");
reopened.Close();
} catch {
error if error.kind == IoErrorKind::NotFound => PrintLine("deleted, as expected"),
error => throw error
}
}
Besides Io, its Rux.toml lists Allocator, FileSystem and Path under [Dependencies].
Run it
cd Examples/Files/File
rux run
wrote Bin/notes.txt
first line
second line
read 23 bytes in 3 reads
deleted, as expected
Common mistakes
Try it yourself
- Change the buffer to 4 bytes, and then to 64. How many reads does the file take each time?
- Open the file a second time with
OpenOptions::Appending(), add a third line, and read the whole file back. - Open a file that does not exist with
OpenOptions::Reading()and let a plaintrypass the error on. Check the exit status withecho $?. - Count the lines as you read, by counting the newline characters in each
buffer[..filled].
Learn more
- Catch and Guard — the tools this lesson combines
- Fallible main — what happens when an error reaches
Main - Buffered I/O — fewer, larger reads and writes
- Atomic file — replacing a file so that no reader ever sees it half-written
loopand Handling errors in the Rux Reference