Darian Moody
Darian Moody

Reputation: 4074

How do you get the size of a file in Elixir?

Given a path to a file on disk, what is the most idiomatic way to retrieve the file size in bytes?

path = "/tmp/some_file.txt"

Upvotes: 19

Views: 4677

Answers (1)

Darian Moody
Darian Moody

Reputation: 4074

This is achieved in Elixir by utilising the builtin stat functions in the File module; here, I will talk about two: File.stat/2 and File.stat!/2.

Both functions return a %File.Stat{} struct for their "value", which we then destructure via pattern matching to pluck out the size field which contains the file size, in bytes. The functions only differ in how they 1) return and 2) handle exceptions (e.g file not found).

For file size checks that throw exceptions (File.Error):

iex(1)> %{size: size} = File.stat! path
1562

For file size checks that handle exceptions gracefully and return an error tuple:

iex(1)> case File.stat path do
...(1)>   {:ok, %{size: size}} -> size
...(1)>   {:error, reason} -> ... # handle error
...(1)> end
1562

N.B: There are other functions that handle slightly differently when dealing with symlinks and are worth knowing about: File.lstat/2 & File.lstat!/2.

Upvotes: 24

Related Questions