寻找Elixir/Erlang内存文件的长度?

5
在Elixir(或Erlang)中,如果我有一个内存文件,如何找到其以字节为单位的长度?
{:ok, fd} = :file.open("", [:ram, :read, :write])
:file.write(fd, "hello")
3个回答

3

如果您正在使用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

感谢@jason-tu!在我的情况下,我必须使用现有的代码,该代码正在使用Erlang的:ram文件。 - jwfearn

3

我不确定是否有更好的方法,但这是我所做的:

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)

2
您可以使用: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}

1
这非常干净,但请注意,在 OTP 中,“:ram_file”模块是官方未记录的,因此随时可能会更改/删除。 - jwfearn

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接