Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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"
like image 856
Darian Moody Avatar asked Oct 12 '15 20:10

Darian Moody


People also ask

How do you find the file size?

Right-click the file and click Properties. The image below shows that you can determine the size of the file or files you have highlighted from in the file properties window. In this example, the chrome. jpg file is 18.5 KB (19,032 bytes), and that the size on disk is 20.0 KB (20,480 bytes).

Which function is used to get the size of a file?

Explanation: The function filesize() returns the size of the specified file and it returns the file size in bytes on success or FALSE on failure.

What is a elixir file?

12.3) This module contains functions to manipulate files. Some of those functions are low-level, allowing the user to interact with files or IO devices, like open/2 , copy/3 and others.

How do I find the size of a file in Kotlin?

If you need the file size in Kilobytes (KB), just divide the length by 1024 . Similarly, to get the file size in Megabytes (MB), divide the result by 1024 * 1024 . That's all about finding a file's size in bytes in Kotlin.


1 Answers

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.

like image 164
Darian Moody Avatar answered Oct 22 '22 10:10

Darian Moody