在Elixir(或Erlang)中,如果我有一个内存文件,如何找到其以字节为单位的长度?
{:ok, fd} = :file.open("", [:ram, :read, :write])
:file.write(fd, "hello")
{:ok, fd} = :file.open("", [:ram, :read, :write])
:file.write(fd, "hello")
如果您正在使用Elixir,您还可以使用StringIO
模块将字符串视为IO设备。 (它基本上是一个RAM文件。)这是一个例子:
# 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
我不确定是否有更好的方法,但这是我所做的:
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
使用方法:
{:ok, fd} = :file.open("", [:ram, :read, :write])
:ok = :file.write(fd, "hello")
{:ok, len} = get_length(fd)
: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}
:ram
文件。 - jwfearn