5

I'm trying to find a good way of reading the first two bytes from a file using Go.

I have some .zip files in my current directory, mixed in with other files.

I would like to loop through all the files in the directory and check if the first two bytes contain the right .zip identifier, namely 50 4B.

What would be a good way to accomplish this using the standard library without having to read the entire file?

Going through the available functions in the io package I managed to find:

func LimitReader(r Reader, n int64) Reader

Which seems to fit my description, it reads from Reader (How do I get a Reader?) but stops after n bytes. Since I'm rather new to Go, I'm not sure how to go about it.

1
  • 1
    os.File which you obtain with os.Open("path") IS a Reader Commented Feb 12, 2017 at 20:13

1 Answer 1

8

You get the initial reader by opening the file. For 2 bytes, I wouldn't use the LimitReader though. Just reading 2 bytes with io.ReadFull is easier.

r, err := os.Open(file)
if err != nil {
    return err
}

defer r.Close()

var header [2]byte
n, err := io.ReadFull(r, header[:])
if err != nil {
    return err
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.