How to read first 60 bytes of a large file?

Hello, guys.

I wanna read first 60 bytes of a large file.

Currently, I have tried File.read!/1 and File.stream!/3.

File.read!/1

It reads entire files. Not what I need.

File.stream!/3

I saw the official example:

# Read in 2048 byte chunks rather than lines
File.stream!("./test/test.data", [], 2048)
#=> %File.Stream{line_or_bytes: 2048, modes: [:raw, :read_ahead, :binary],
#=>   path: "./test/test.data", raw: true}

Even if it reads one chunk whose size is 2048 byte every time, It always streams entire file.

Last

How to read the first 60 bytes of a large file?

1 Like

Perhaps you are looking for IO.binread/2.

Failing that look at :file.read/2.

8 Likes

To be fair, you can still use the File.stream even if you don’t want the whole file.

File.stream!("./test/test.data", [], 60)
|> Enum.take(1)

gives you a list of a single binary of 60 bytes and doesn’t read the rest of the file.

But the tips you got already also work.

10 Likes

Thanks! @peerreynders @jola :grin: