简体   繁体   English

如何在Elixir(或Erlang)中读取文件的一部分?

[英]How to read a portion of a file in Elixir (or Erlang)?

How can we read only a selected portion of a file? 我们怎样才能只读取文件的选定部分?

Like this: Read(file, start, length) 像这样: Read(file, start, length)

You can use :file.position/2 and :file.read/2 . 您可以使用:file.position/2:file.read/2

With: 附:

$ seq 10 > 10.txt

and code: 和代码:

{:ok, file} = :file.open("10.txt", [:read, :binary])
:file.position(file, 5)
IO.inspect :file.read(file, 10)

The output is: 输出是:

{:ok, "\n4\n5\n6\n7\n8"}

That's 10 bytes starting at the 6th byte. 那是从第6个字节开始的10个字节。

It would be handy if you read the documentation . 如果你阅读文档会很方便。 For example file:pread/2,3 . 例如file:pread/2,3

read(File, Start, Length) ->
    {ok, F} = file:open(File, [binary]),
    try file:pread(F, [{Start, Length}]) of
        {ok, [Data]} -> Data
    after file:close(F)
    end.

This would be the code that Hynek shared transcribed to Elixir. 这将是Hynek共享转录给Elixir的代码。 I only post it as an answer because it's a bit long to put into a comment. 我只是将其作为答案发布,因为评论时间有点长。

def read(file, start, length) do
  {ok, f} = :file.open(file, [:binary])
  {ok, data} = :file.pread(f, start, length)
  :file.close(f)
  data
end

Yes, granted it'd be nice to have this in the Elixir file module. 是的,授予它在Elixir文件模块中有这个很好。 If you really want it there @CharlesO, why don't you go ahead and create a pull request? 如果你真的想要它@CharlesO,你为什么不继续创建拉取请求? Jose and the other core committers are some of the friendliest folks I've run across in years and years of software development. 何塞和其他核心提交者是我在多年和多年的软件开发中遇到过的最友善的人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM