Files and IO

Most Erlang services keep their state in a process and their data in a database, and every one of them still reads a configuration file, writes a log or imports a dump. The file module gives two shapes for that: the whole file in one call, for something small, and a handle with a read loop, for something that does not fit in memory. Both answer a value the caller matches, because a file system error is an expected answer and not an exception.

Write a file

file:write_file/2 replaces a file with the data of one call, and the append option of file:write_file/3 adds to its end instead. The data is iodata: a binary, a string, or a list that mixes both, which means a list of lines needs no join and no copy. The program below is a small notebook that treats a missing file as an empty one:

notes.erl

-module(notes). -export([add/1, all/0, count/0, remove/0, main/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()). main() -> _ = remove(), io:format("empty: ~p~n", [all()]), ok = add("buy milk"), ok = add("call Ada"), io:format("all: ~p~n", [all()]), io:format("count: ~p~n", [count()]), {ok, Bin} = file:read_file(file_name()), io:format("bytes: ~p~n", [Bin]), ok = remove().

erlc notes.erl

erl -noshell -eval 'notes:main(), halt().'

empty: [] all: ["buy milk","call Ada"] count: 2 bytes: <<"buy milk\ncall Ada\n">>

Every function answers a value the caller can match: ok when the write worked, a list for the notes. Nothing raises, because a file system error is a normal answer. The first call deletes a file that may not exist, and the result is ignored on purpose: file:delete/1 answers {error, enoent} there, and a notebook that starts empty is not an error.

Read it back

file:read_file/1 reads the whole file into a binary and answers {ok, Binary}. The binary tools of the binaries in depth lesson take over from there, and the split in all/0 is the simplest way to turn the file into lines. The last line of the run shows both layers: the list the module answers, and the bytes the file really holds, newline at the end included.

Line by line

A whole file in memory is fine for a notebook and wrong for a log of a gigabyte. file:open/2 gives a handle, and file:read_line/1 takes one line per call. Open with binary in the mode list to get binaries instead of strings, and close the handle when the loop ends. The program reads two lines, the end of the file, and then makes the mistake on purpose:

lines.erl

-module(lines). -export([main/0]). main() -> ok = file:write_file("lines.txt", "first\nsecond\n"), {ok, Handle} = file:open("lines.txt", [read, binary]), io:format("line 1: ~p~n", [file:read_line(Handle)]), io:format("line 2: ~p~n", [file:read_line(Handle)]), io:format("end: ~p~n", [file:read_line(Handle)]), ok = file:close(Handle), io:format("after close: ~p~n", [file:read_line(Handle)]).

erlc lines.erl

erl -noshell -eval 'lines:main(), halt().'

line 1: {ok,<<"first\n">>} line 2: {ok,<<"second\n">>} end: eof after close: {error,terminated}

At the end of a healthy file the call answers eof, which ends the loop. After file:close/1 the handle is dead, and a read on it answers {error, terminated}: a loop that closes a handle inside itself and then reads again sees exactly that line, and the fix is one close at the end and no other.

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/1 checks without opening anything, and it answers a boolean rather than a tuple:

missing.erl

-module(missing). -export([main/0]). main() -> _ = file:delete("nowhere.txt"), io:format("missing: ~p~n", [file:read_file("nowhere.txt")]), io:format("directory: ~p~n", [file:read_file(".")]), io:format("is_file: ~p~n", [filelib:is_file("nowhere.txt")]).

erlc missing.erl

erl -noshell -eval 'missing:main(), halt().'

missing: {error,enoent} directory: {error,eisdir} is_file: false

The lesson of the second line is that a directory is not an empty file: a program that reads a path a user gave it must expect eisdir as well as enoent. The file IO in depth lesson adds the chunked read and the random access a large file needs.

A folder

filelib:fold_files/5 walks a tree and calls a function for every file that matches a regular expression. The argument true asks for the subdirectories as well, and the accumulator is whatever the caller makes it. This program builds a small tree and lists its text files:

walk.erl

-module(walk). -export([main/0]). main() -> ok = filelib:ensure_dir("tree/a/two.txt"), ok = file:write_file("tree/one.txt", "1\n"), ok = file:write_file("tree/a/two.txt", "2\n"), Files = filelib:fold_files("tree", ".*[.]txt$", true, fun(File, Acc) -> [File | Acc] end, []), io:format("files: ~p~n", [lists:sort(Files)]).

erlc walk.erl

erl -noshell -eval 'walk:main(), halt().'

files: ["tree/a/two.txt","tree/one.txt"]

filelib:ensure_dir/1 creates every folder the path needs and answers ok when they all exist, which is the one call a program needs before it writes a file into a tree it made. The filter is an ordinary regular expression, so the same walk selects .beam files, .config files or everything, and the regular expressions lesson reads the syntax.

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.

  4. What does this module print? -module(q4). -export([main/0]). main() -> R1 = file:read_file("."), R2 = filelib:is_regular("."), io:format("~p~n", [{R1, R2}]).

    Answer

    {{error,eisdir},false}

    A directory is not a file, so the read fails with eisdir and the regular-file check answers false.

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

    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. What does this module print? -module(q1). -export([main/0]). main() -> ok = file:write_file("a.txt", "alpha\n"), ok = file:write_file("a.txt", "beta\n", [append]), {ok, Bin} = file:read_file("a.txt"), {ok, Handle} = file:open("a.txt", [read, binary]), Line = file:read_line(Handle), ok = file:close(Handle), io:format("~p~n", [{Bin, Line}]).

    Answer

    {<<"alpha\nbeta\n">>,{ok,<<"alpha\n">>}}

    The append keeps the first write, so the file holds both lines, and the first read gives the first line.

  9. What does this module print? -module(q2). -export([main/0]). main() -> R1 = file:read_file("nothing.txt"), R2 = filelib:is_file("nothing.txt"), io:format("~p~n", [{R1, R2}]).

    Answer

    {{error,enoent},false}

    A missing file is an error tuple, and the cheap check answers the boolean false.

  10. What does this module print? -module(q3). -export([main/0]). main() -> ok = filelib:ensure_dir("d/sub/f.txt"), ok = file:write_file("d/sub/f.txt", "x"), io:format("~p~n", [filelib:is_regular("d/sub/f.txt")]).

    Answer

    true

    ensure_dir created the folders and the write made the file, so it is a regular file.

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