File IO in depth
In Erlang the files lesson reads a whole file and takes it apart; this one keeps the file on disk. Three tools cover almost every real job: a read loop that takes a fixed number of bytes at a time, a read or a write at a position the program chooses, and an encoding that turns bytes into characters. All three work on a handle from file:open/2, and all three answer the same error tuples as the calls of the simpler lesson.
Chunks
file:read(Handle, Size) answers the next Size bytes, or fewer when the file ends first, and eof when there is nothing left. The loop below reads a twelve byte file five bytes at a time, which shows both the short read and the end of the stream. The raw mode is the one to add for a bulk read: it takes the io server of the process out of the path, so the bytes travel from the file system to the caller without a relay process:
chunks.erl
-module(chunks). -export([main/0]). main() -> ok = file:write_file("data.bin", <<"abcdefghijkl">>), {ok, Handle} = file:open("data.bin", [read, binary, raw]), ok = read_chunks(Handle, 5), ok = file:close(Handle). read_chunks(Handle, Size) -> case file:read(Handle, Size) of {ok, Chunk} -> io:format("~p bytes: ~p~n", [byte_size(Chunk), Chunk]), read_chunks(Handle, Size); eof -> io:format("eof~n"), ok end.
erlc chunks.erl
erl -noshell -eval 'chunks:main(), halt().'
5 bytes: <<"abcde">> 5 bytes: <<"fghij">> 2 bytes: <<"kl">> eof
The last read is short because the file ended, not because the disk failed: a read loop must accept a chunk of any size and only eof ends it. The chunk size is a trade: a few kilobytes fit a cache line and keep the loop cheap, a megabyte wastes memory on a small file and a byte at a time turns a large file into a long loop. The performance lesson measures the choice instead of guessing it.
Random access
file:pread(Handle, Position, Length) reads without moving the file pointer, and file:pwrite(Handle, Position, Data) writes at a position. Both count from zero. A write does not shift what follows: the bytes are replaced one for one, so a write longer than the field it replaces overwrites the neighbours, which is the mistake the program shows on purpose:
pread.erl
-module(pread). -export([main/0]). main() -> ok = file:write_file("record.txt", <<"name: Ada\nrole: coder\n">>), {ok, Handle} = file:open("record.txt", [read, write, binary]), {ok, Old} = file:pread(Handle, 6, 3), ok = file:pwrite(Handle, 6, <<"Grace">>), {ok, New} = file:pread(Handle, 6, 5), ok = file:close(Handle), io:format("before: ~p~n", [Old]), io:format("after: ~p~n", [New]), {ok, Whole} = file:read_file("record.txt"), io:format("file: ~p~n", [Whole]).
erlc pread.erl
erl -noshell -eval 'pread:main(), halt().'
before: <<"Ada">> after: <<"Grace">> file: <<"name: Graceole: coder\n">>
The file now reads name: Graceole: coder: five bytes of Grace replaced three bytes of Ada, and the two characters that were left of role stayed where they were. A fixed size field is safe to overwrite; a variable length one is not, and a format with a length prefix or one record per line exists to make a value longer without moving the rest. The term formats lesson shows a file of whole terms, which sidesteps the question.
Unicode
In binary mode a file is bytes: a character outside ASCII arrives as several bytes, and counting bytes and counting characters are different questions. The {encoding, unicode} option makes the handle a character device instead: io:get_line/2 answers a string of characters and io:format/3 writes them as UTF-8. The program writes one word with an accent and reads it back both as bytes and as characters:
unicode_file.erl
-module(unicode_file). -export([main/0]). main() -> {ok, Out} = file:open("hello.txt", [write, {encoding, unicode}]), ok = io:format(Out, "caf\x{e9}~n", []), ok = file:close(Out), {ok, Bytes} = file:read_file("hello.txt"), io:format("bytes: ~p, size: ~p~n", [list_to_tuple(binary_to_list(Bytes)), byte_size(Bytes)]), {ok, In} = file:open("hello.txt", [read, {encoding, unicode}]), Line = io:get_line(In, ""), ok = file:close(In), io:format("line: ~p~n", [Line]), io:format("length: ~p~n", [length(Line)]).
erlc unicode_file.erl
erl -noshell -eval 'unicode_file:main(), halt().'
bytes: {99,97,102,195,169,10}, size: 6 line: "café\n" length: 5
Six bytes and five characters: the é takes two bytes in UTF-8 and one character in the string. \x{e9} is the escape for a character by code point, which is the portable way to write a non ASCII character in Erlang source. The encodings lesson covers the modules that convert between the two views of the same data.
The wrong mode
The mode list of file:open/2 decides what a handle can do, and a call that does not fit answers an error tuple instead of raising. A handle opened for writing cannot be read, and a handle that was closed is dead whatever it was opened for:
bad_mode.erl
-module(bad_mode). -export([main/0]). main() -> {ok, Handle} = file:open("write_only.txt", [write]), io:format("read on a write handle: ~p~n", [file:read(Handle, 1)]), ok = file:close(Handle), io:format("read after close: ~p~n", [file:read(Handle, 1)]), ok = file:delete("write_only.txt").
erlc bad_mode.erl
erl -noshell -eval 'bad_mode:main(), halt().'
read on a write handle: {error,ebadf} read after close: {error,terminated}
ebadf is the operating system saying that the descriptor is not open for that operation, and terminated is the runtime saying that the handle it knew is gone. Both are answers, not exceptions, and a program that reads a configuration file it also writes opens it with [read, write] or closes it between the two jobs.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
file:read(Handle, N)answer at the end of a file?Answer
eofThe atom eof is the normal end of the stream; a short chunk before it is normal too.
-
What does the
rawmode remove from a file read?Answer
The io server process in the path
The bytes go from the file system to the caller without a relay process.
-
What does
file:pwrite(Handle, Position, Data)do to the bytes after the write?Answer
It replaces them one for one
The write replaces bytes at the position, so the length of the data decides how many are overwritten.
-
What does
{encoding, unicode}change about a handle?Answer
It turns the handle into a character device
Reads answer characters and writes encode them as UTF-8 instead of raw bytes.
-
What does a read on a handle opened only for writing answer?
Answer
{error, ebadf}The descriptor is not open for reading, and the operating system says so.
-
Why is a chunked read better than
file:read_file/1for a large file?Answer
It never holds the whole file in memory
The loop keeps one chunk at a time, so the memory of the process does not grow with the file.
-
What does this module print?
-module(q1). -export([main/0]). main() -> ok = file:write_file("d.bin", <<"abcdefg">>), {ok, H} = file:open("d.bin", [read, binary, raw]), A = file:read(H, 3), B = file:read(H, 3), C = file:read(H, 3), D = file:read(H, 3), ok = file:close(H), io:format("~p~n", [A]), io:format("~p~n", [B]), io:format("~p~n", [C]), io:format("~p~n", [D]).Answer
{ok,<<"abc">>}/{ok,<<"def">>}/{ok,<<"g">>}/eofSeven bytes in chunks of three give 3, 3, 1 and then eof.
-
What does this module print?
-module(q2). -export([main/0]). main() -> ok = file:write_file("r.txt", <<"name: Ada\n">>), {ok, H} = file:open("r.txt", [read, write, binary]), ok = file:pwrite(H, 6, <<"Bo">>), {ok, Bin} = file:read_file("r.txt"), ok = file:close(H), io:format("~p~n", [Bin]).Answer
<<"name: Boa\n">>Two bytes replace two bytes at the position, and the length of the file does not change.
-
What does this module print?
-module(q3). -export([main/0]). main() -> {ok, Out} = file:open("u.txt", [write, {encoding, unicode}]), ok = io:format(Out, "caf\x{e9}~n", []), ok = file:close(Out), {ok, Bin} = file:read_file("u.txt"), io:format("~p~n", [byte_size(Bin)]).Answer
6Four ASCII letters, the two bytes of the accented character and the newline make six.
-
What does this module print?
-module(q4). -export([main/0]). main() -> ok = file:write_file("w.txt", "x"), {ok, H} = file:open("w.txt", [write]), ok = file:close(H), io:format("~p~n", [file:read(H, 1)]).Answer
{error, terminated}The handle was closed, so the runtime reports it as terminated before the mode is ever consulted.
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.
Автор статьи: Arthur Isaev