← Back to lesson 20: Read and write one real file

Read and write one real file: full examples and further reading

The original lesson material is preserved here for reference. The main notebook focuses on this lesson's core question.

Build a path, write UTF-8 text, and handle the tagged read result.

Write two lines to a temporary file, read them back, and count the lines.

Run this first

Run it once, change one input, and compare the new result.

Original full example
# Write and read one temporary UTF-8 file
path = Path.join(System.tmp_dir!(), "beam-path-note.txt")
:ok = File.write(path, "north
south
")
{:ok, text} = File.read(path)
{path, String.split(text, "
", trim: true)}

The tuple contains the temporary path and ["north", "south"].

Steps for the full example

  1. Read Path.join/2: Join path segments for the current operating system.
  2. Read File.write/2: Write bytes and return a tagged result.
  3. Read File.read/1: Read the file and return tagged data.

Original lesson notes

Run the example first. Predict one result, then change one input and run it again.

Path.join/2 builds a platform-safe path instead of joining strings by hand.

Non-bang File functions return {:ok, data} or {:error, reason}.

Symbols and terms
Path.join/2
Join path segments for the current operating system.
File.write/2
Write bytes and return a tagged result.
File.read/1
Read the file and return tagged data.
path
Path.join/2 builds a platform-safe path instead of joining strings by hand.
tagged file result
Non-bang File functions return {:ok, data} or {:error, reason}.
resource boundary
Files belong outside pure transformation functions so errors and cleanup stay visible.

Original full exercise

Append east to the same file and read it again.

Exercise starter
:ok = File.write(path, "east
", ____)
File.read(path)

Use append mode and receive {:ok, text}.

Show hint

Pass [:append] as the third argument.

Show original answer
Reference answer
:ok = File.write(path, "east
", [:append])
File.read(path)
Why use Path.join instead of a hard-coded slash?

It builds a valid path on different operating systems.

Original lesson takeaways
Design trade-offs and language comparisons
Original course references