问题
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")
回答1:
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)
回答2:
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}
回答3:
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
来源:https://stackoverflow.com/questions/43770144/find-length-of-elixir-erlang-in-memory-file