Files and IO

The File module of Elixir reads and writes whole files in one call. Every function comes twice: the plain name answers an ok or error tuple, and the name with ! answers the value or raises a File.Error. The module works on paths; the paths lesson covers the folders around them, and streams over files the file that is too large to read at once.

Write and read

File.write!/2 writes a binary to a path and answers :ok. File.read/1 answers the pair and File.read!/1 the binary itself. The inspector shows the newlines of the text as escapes:

write.exs

File.write!("notes.txt", "first line\nsecond line\n") IO.inspect(File.read("notes.txt")) IO.inspect(File.read!("notes.txt")) File.rm!("notes.txt")

elixir write.exs

{:ok, "first line\nsecond line\n"}
"first line\nsecond line\n"

The two calls give the same text in two shapes, and the program removes the file at the end so that a second run starts clean. A relative path is resolved against the working directory of the program, which is the folder the command runs in; File.cwd!/0 answers it when a program needs to show the user where it wrote.

The bang versions

A file that is not there is the expected failure of this module, so both forms exist and the caller chooses. The program below reads the same missing file twice: the plain call answers the reason, and the bang call stops with an exception that names the path:

missing.exs

IO.inspect(File.read("missing.txt")) File.read!("missing.txt")

elixir missing.exs

{:error, :enoent}
** (File.Error) could not read file "missing.txt": no such file or directory
    (elixir 1.19.7) lib/file.ex:435: File.read!/1
    missing.exs:3: (file)

:enoent is the atom the operating system error becomes, and File.Error carries the path and the reason as fields, so a program that rescues it can report both. A library that reads a file the caller named usually answers the tuple; a script that cannot continue without the file uses the bang call.

Append, and the file that exists

The third argument of File.write/3 is the list of modes, and :append adds to the end instead of replacing the text. File.exists?/1 answers whether the path is a file that can be opened:

append.exs

File.write!("log.txt", "one\n") File.write!("log.txt", "two\n", [:append]) IO.inspect(File.read!("log.txt")) IO.inspect(File.exists?("log.txt")) File.rm!("log.txt")

elixir append.exs

"one\ntwo\n"
true

The modes are those of the file handling of Erlang: :append, :exclusive to fail when the file exists, :sync to wait for the disk. A program that logs appends, and a program that writes a report replaces; the difference is the list, not another function.

The mistake: a write into a folder that is not there

Writing a file does not create the folder it lives in. A path whose directory is missing stops with a File.Error that names the path it tried, and the reason is the same :enoent the read of a missing file answers:

mistake.exs

File.write!("missing/notes.txt", "hi")

elixir mistake.exs

** (File.Error) could not write to file "missing/notes.txt": no such file or directory
    (elixir 1.19.7) lib/file.ex:1407: File.write!/3
    mistake.exs:1: (file)

The fix is File.mkdir_p!/1 on the folder before the write, which creates every level that is missing and succeeds when the folder is already there. A program that writes into a folder the user named should do that once, at start-up, rather than after the first failure.

The programs on this page were run with Elixir 1.19.7 on Erlang/OTP 27 (erts 15.2.7.14), on Linux x86_64 in a Docker container.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does File.read/1 answer for a file that is not there?

    Answer

    {:error, :enoent}

    The plain call answers the error tuple, and the bang call raises instead.

  2. What does the :append mode change?

    Answer

    the text is added at the end instead of replacing the file

    The mode list of File.write/3 decides what the call does with an existing file.

  3. Does File.write!/2 create the folder of the path?

    Answer

    no, and a missing folder raises a File.Error

    The folder is made by File.mkdir_p!/1; the write expects it to be there.

  4. What is :enoent?

    Answer

    the atom an operating system error becomes

    Erlang and Elixir turn errno codes into atoms such as :enoent and :eacces.

  5. What does this program print? File.write!("t.txt", "hi") IO.inspect(File.read("t.txt")) File.rm!("t.txt")

    Answer

    {:ok, "hi"}

    The read of a file that exists answers the ok tuple with its content.

  6. What does this program print? IO.inspect(File.read("missing.txt"))

    Answer

    {:error, :enoent}

    The plain read answers the pair, whose second item is the reason.

  7. What does this program do? File.read!("missing.txt")

    Answer

    A File.Error, because the path does not exist

    The bang call raises, and its exception names the path and the reason.

  8. What does this program print? File.write!("t.txt", "a") File.write!("t.txt", "b", [:append]) IO.inspect(File.read!("t.txt")) File.rm!("t.txt")

    Answer

    "ab"

    The second write appends, so the file holds both texts.

  9. What does this program print? File.write!("t.txt", "x") IO.inspect(File.exists?("t.txt")) File.rm!("t.txt")

    Answer

    true

    The file was written, so the path is a file that can be opened.

  10. What does this program do? File.write!("missing/notes.txt", "hi")

    Answer

    A File.Error, because the folder of the path does not exist

    The write does not make folders, and the missing folder stops it with a File.Error.

Автор статьи: Arthur Isaev

Изображение баннера