← Back to lesson 19: Read and write one file safely

Read and write one file safely: 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 bytes, and match the result of reading them back.

Write a small text file and handle both the success and error branches of file:read_file/1.

Run this first

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

Original full example
%% Keep the path and both IO results visible
Path = filename:join(["tmp", "note.txt"]),
ok = filelib:ensure_dir(Path),
ok = file:write_file(Path, <<"ready\n">>),
file:read_file(Path).

The final call returns {ok,<<"ready\n">>} when the file is readable.

Steps for the full example

  1. Read filename:join/1: Join path pieces for the current operating system.
  2. Read file:write_file/2: Write iodata to a file.
  3. Read file:read_file/1: Read a whole file as a binary result.

Original lesson notes

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

A path names a place in the file system; filename:join/1 builds it without hand-written separators.

file:read_file/1 returns file contents as a binary when it succeeds.

Symbols and terms
filename:join/1
Join path pieces for the current operating system.
file:write_file/2
Write iodata to a file.
file:read_file/1
Read a whole file as a binary result.
path
A path names a place in the file system; filename:join/1 builds it without hand-written separators.
binary file data
file:read_file/1 returns file contents as a binary when it succeeds.
IO result
File functions return {ok, Value}, ok, or {error, Reason} instead of hiding failure.

Original full exercise

Match a missing-file error without crashing.

Exercise starter
case file:read_file("missing.txt") of
  {ok, Data} -> {ok, Data};
  {error, ____} -> missing
end.

Bind the reason to enoent.

Show hint

The common missing-file reason is the atom enoent.

Show original answer
Reference answer
case file:read_file("missing.txt") of
  {ok, Data} -> {ok, Data};
  {error, enoent} -> missing
end.
Why use filename:join/1?

It keeps path construction readable and portable across operating systems.

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