Erlang basics · Lesson 19 (open contents)
Read and write one file safely
Build a path, write bytes, and match the result of reading them back.
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.
Read from the first line down
- 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.
Symbols are not secret signs
filename:join/1Join path pieces for the current operating system.
file:write_file/2Write iodata to a file.
file:read_file/1Read a whole file as a binary result.
Match each name to its meaning
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.
Why these forms are useful
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.
Close the answer and try
Match a missing-file error without crashing.
case file:read_file("missing.txt") of
{ok, Data} -> {ok, Data};
{error, ____} -> missing
end.Target result: Bind the reason to enoent.
Stuck? Read one hint
The common missing-file reason is the atom enoent.
After you run it, see one answer
case file:read_file("missing.txt") of
{ok, Data} -> {ok, Data};
{error, enoent} -> missing
end.Think about it: Why use `filename:join/1`?
It keeps path construction readable and portable across operating systems.
Remember these three lines
- 1
Build paths with
filename. - 2
Match file results.
- 3
Keep external IO at a clear boundary.