Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find length of Elixir/Erlang in-memory file?

In Elixir (or Erlang), if I have an in-memory file, how do I find its length in bytes?

{:ok, fd} = :file.open("", [:ram, :read, :write])
:file.write(fd, "hello")
like image 279
jwfearn Avatar asked May 03 '17 21:05

jwfearn


3 Answers

Not sure if there's a better way, but this is what I did:

def get_length(fd) do
  {:ok, cur} = :file.position(fd, {:cur, 0})
  try do
    :file.position(fd, {:eof, 0})
  after
    :file.position(fd, cur)
  end
end

Usage:

{:ok, fd} = :file.open("", [:ram, :read, :write])
:ok = :file.write(fd, "hello")
{:ok, len} = get_length(fd)
like image 183
jwfearn Avatar answered Oct 31 '22 10:10

jwfearn


If you're using Elixir, you can also use the StringIO module to treat strings as IO devices. (It's basically a RAM file.) Here's an example:

# create ram file
{:ok, pid} = StringIO.open("")

# write to ram file
IO.write(pid, "foo")
IO.write(pid, "bar")

# read ram file contents
{_, str} = StringIO.contents(pid)

# calculate length
str |> byte_size     |> IO.inspect # number of bytes
str |> String.length |> IO.inspect # number of Unicode graphemes
like image 37
nucleartide Avatar answered Oct 31 '22 10:10

nucleartide


You can use :ram_file.get_size/1:

iex(1)> {:ok, fd} = :file.open("", [:ram, :read, :write])
{:ok, {:file_descriptor, :ram_file, #Port<0.1163>}}
iex(2)> :file.write(fd, "hello")
:ok
iex(3)> :ram_file.get_size(fd)
{:ok, 5}
iex(4)> :file.write(fd, ", world!")
:ok
iex(5)> :ram_file.get_size(fd)
{:ok, 13}
like image 35
Dogbert Avatar answered Oct 31 '22 11:10

Dogbert