← Cookbook Files and processes Beginner · Pooka 0.5.0

Read and write files

Write a file, add to it, read it back and tidy up, with one ? per step and one place to handle every failure.

You will use

  • pooka/file: write, append, read, delete, each returning a Result
  • FileError, with the path and a message
  • ? to stop at the first error

The whole program

src/main.pooka
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

  1. Every file operation can fail. Disks fill up, files go missing, permissions say no. So every function in pooka/file returns a Result with a FileError.
  2. ? keeps the happy path straight. In keep_notes, each ? either unwraps the Ok or returns the Error straight away. Four steps, no nesting.
  3. Handle it once, at the top. main matches on the whole result and prints the path and message if anything went wrong.
  4. 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.