You will use
pooka/file:write,append,read,delete, each returning aResultFileError, with thepathand amessage?to stop at the first error
The whole program
module main
import pooka/file.{FileError}
import pooka/io
keep_notes(path: String) -> Result(String, FileError) {
file.write(path, "Remember the kettle.\n")?
file.append(path, "Feed the owl.\n")?
let notes = file.read(path)?
file.delete(path)?
Ok(notes)
}
main() {
match keep_notes("notes.txt") {
Ok(notes) -> {
io.print(notes)
Nil
}
Error(problem) -> {
io.eprintln(problem.path + ": " + problem.message)
Nil
}
}
match file.read("missing.txt") {
Ok(_) -> Nil
Error(problem) -> {
io.println(
"Could not read " + problem.path + ": " + problem.message
)
Nil
}
}
}
Run it
$ pooka run
Remember the kettle.
Feed the owl.
Could not read missing.txt: enoent
How it works
- Every file operation can fail. Disks fill up, files go missing, permissions say no. So every function in
pooka/filereturns aResultwith aFileError. ?keeps the happy path straight. Inkeep_notes, each?either unwraps theOkor returns theErrorstraight away. Four steps, no nesting.- Handle it once, at the top.
mainmatches on the whole result and prints the path and message if anything went wrong. - Messages come from the BEAM. A missing file says
enoent("error, no entry"), the name Erlang gives it. You can match on it to say something gentler.
Try next: file.read_bytes and file.write_bytes work with BitArray for images and other binary files. file.exists asks before you touch.