Files and IO
Write a file
file:write_file writes a whole file in one call, and the append flag adds to the end instead of replacing it. The data is iodata: a binary, a string, or a list that mixes both. Save this module as notes.erl.
-module(notes).
-export([add/1, all/0, count/0, remove/0]).
file_name() ->
"notes.txt".
add(Text) ->
file:write_file(file_name(), [Text, "\n"], [append]).
all() ->
case file:read_file(file_name()) of
{ok, Bin} ->
[binary_to_list(Line)
|| Line <- binary:split(Bin, <<"\n">>, [global]),
Line =/= <<>>];
{error, enoent} ->
[]
end.
count() ->
length(all()).
remove() ->
file:delete(file_name()).
Every function answers a value the caller can match: ok when the write worked, a list for the notes. Nothing throws, because a file system error is a normal answer, not an exception.
Read it back
file:read_file reads the whole file into a binary and answers {ok, Binary}, so the text module of lesson 8 and the binary tools of lesson 28 take over from there. The notes module hides the split, and the shell shows both layers.
erlc notes.erl
erl
1> notes:all().
[]
2> notes:add("buy milk").
ok
3> notes:add("call Ada").
ok
4> notes:all().
["buy milk","call Ada"]
5> notes:count().
2
6> file:read_file("notes.txt").
{ok,<<"buy milk\ncall Ada\n">>}
The first call answers the empty list rather than an error: a missing file is the same as an empty notebook, and the case clause in all/0 decides that.
Line by line
A whole file in memory is fine for a notebook and wrong for a log of a gigabyte. file:open gives a handle, and file:read_line takes one line per call. Open with binary in the mode list to get binaries instead of strings, and always close the handle.
erl
1> {ok, F} = file:open("notes.txt", [read, binary]), {ok, First} = file:read_line(F), file:close(F), First.
<<"buy milk\n">>
2> file:read_line(F).
{error,terminated}
The second call is the mistake to remember: the handle is closed, so read_line answers {error, terminated} instead of another line. At the end of a healthy file the same call answers eof.
Missing files
File errors come back as an atom in an error tuple, and the atom names the reason: enoent is no such file or directory, eacces is a permission problem, eisdir is a folder where a file was expected. filelib:is_file checks without opening anything.
erl
1> file:read_file("missing.txt").
{error,enoent}
2> filelib:is_file("notes.txt").
true
3> notes:remove().
ok
4> file:read_file("notes.txt").
{error,enoent}
Next: Sockets
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
file:read_file/1answer for a file that exists?Answer
{ok, Binary}The whole content arrives as a binary inside an ok tuple.
-
What does the
appendoption offile:write_file/3do?Answer
Creates the file or adds to its end
Without append the file is replaced; with it the new data goes after the old bytes.
-
What does the atom
enoentmean?Answer
No such file or directory
It is the POSIX reason for a missing file, short for error no entity.
-
What does
file:read_file("missing.txt")answer?Answer
{error, enoent}A missing file is a normal error tuple, not an exception.
-
Which call opens a file for line by line reading?
Answer
file:open/2file:openanswers a handle, andfile:read_linethen takes one line per call. -
What does
file:read_line/1answer at the end of a file?Answer
eofThe atom eof marks the normal end; an error tuple means a real problem.
-
Why does the closed handle answer
{error, terminated}?Answer
The handle is no longer open
After
file:closethe handle is dead, so a read on it is reported as terminated. -
Which mode list gives binaries from
file:read_line/1?Answer
[read, binary]Without binary the line comes back as a string; the binary flag keeps it as bytes.
-
Which call checks that a path is a file without opening it?
Answer
filelib:is_file/1filelib:is_file/1answers true or false and touches nothing. -
What does
notes:all/0answer when the notebook file does not exist?Answer
[]The
{error, enoent}clause of the case returns the empty list, so a new notebook reads as empty.
The examples on this page were compiled and run with Erlang/OTP 27 (erts-15.2.7.14) on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev