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.

  1. What does file:read_file/1 answer for a file that exists?

    Answer

    {ok, Binary}

    The whole content arrives as a binary inside an ok tuple.

  2. What does the append option of file:write_file/3 do?

    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.

  3. What does the atom enoent mean?

    Answer

    No such file or directory

    It is the POSIX reason for a missing file, short for error no entity.

  4. What does file:read_file("missing.txt") answer?

    Answer

    {error, enoent}

    A missing file is a normal error tuple, not an exception.

  5. Which call opens a file for line by line reading?

    Answer

    file:open/2

    file:open answers a handle, and file:read_line then takes one line per call.

  6. What does file:read_line/1 answer at the end of a file?

    Answer

    eof

    The atom eof marks the normal end; an error tuple means a real problem.

  7. Why does the closed handle answer {error, terminated}?

    Answer

    The handle is no longer open

    After file:close the handle is dead, so a read on it is reported as terminated.

  8. 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.

  9. Which call checks that a path is a file without opening it?

    Answer

    filelib:is_file/1

    filelib:is_file/1 answers true or false and touches nothing.

  10. What does notes:all/0 answer 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

Banner image