data-structuresioelixirfile-accesslseek

How to do an lseek on an open file, and read N bytes?


I'd like to use Elixir to read a binary file that has a fixed-length header, and data structures within that are of determinable length. These files can be huge, and I really don't want to be forced to read the entire thing to memory. Maybe my search-fu is lacking, but I didn't find anything like this in the docs or elsewhere.


Solution

  • From the File docs:

    to read from a specific position in a file, use :file.pread/3:

    File.write!("example.txt", "Eats, Shoots & Leaves")
    file = File.open!("example.txt")
    :file.pread(file, 15, 6)
    #=> {:ok, "Leaves"}
    

    Alternatively, if you need to keep track of the current position, use :file.position/2 and :file.read/2:

    :file.position(file, 6)
    #=> {:ok, 6}
    :file.read(file, 6)
    #=> {:ok, "Shoots"}
    :file.position(file, {:cur, -12})
    #=> {:ok, 0}
    :file.read(file, 4)
    #=> {:ok, "Eats"}