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"
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).
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With