简体   繁体   中英

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)

You can use :file.position/2 and :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.

It would be handy if you read the documentation . For example 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. 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. If you really want it there @CharlesO, why don't you go ahead and create a pull request? Jose and the other core committers are some of the friendliest folks I've run across in years and years of software development.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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