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.
%% 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
- Read
filename:join/1: Join path pieces for the current operating system. - Read
file:write_file/2: Write iodata to a file. - 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/1builds it without hand-written separators. - binary file data
file:read_file/1returns 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.
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
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
- Build paths with
filename. - Match file results.
- Keep external IO at a clear boundary.