【问题标题】:Find length of Elixir/Erlang in-memory file?查找 Elixir/Erlang 内存文件的长度?
【发布时间】:2017-10-01 21:09:02
【问题描述】:

在 Elixir(或 Erlang)中,如果我有一个内存文件,我如何找到它的字节长度?

{:ok, fd} = :file.open("", [:ram, :read, :write])
:file.write(fd, "hello")

【问题讨论】:

    标签: elixir erlang-otp


    【解决方案1】:

    如果您使用 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 文件的现有代码。
    【解决方案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}
    

    【讨论】:

    • 这很干净,但请注意 :ram_file 模块在 OTP 中没有正式记录,因此随时可能更改/删除。
    【解决方案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)
    

    【讨论】:

      猜你喜欢
      • 2023-01-13
      • 1970-01-01
      • 2011-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-23
      • 1970-01-01
      相关资源
      最近更新 更多