从文件中高效地读取前两个字节 – Golang

huangapple go评论71阅读模式
英文:

Reading the first two bytes from a file efficiently - Golang

问题

我正在尝试找到一种使用Go语言从文件中读取前两个字节的好方法。

我当前目录中有一些.zip文件,与其他文件混在一起。

我想遍历目录中的所有文件,并检查前两个字节是否包含正确的.zip标识符,即50 4B

在不必读取整个文件的情况下,有什么好的方法可以使用标准库来实现这一点呢?

io包中的可用函数中,我找到了以下函数:

func LimitReader(r Reader, n int64) Reader

这个函数似乎符合我的描述,它从Reader中读取(我如何获得一个Reader?),但在读取了n个字节后停止。由于我对Go语言还比较新手,我不太确定该如何操作。

英文:

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

得分: 8

你可以通过打开文件来获取初始读取器。对于2个字节,我不会使用LimitReader。使用io.ReadFull函数来读取2个字节更简单。

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
}
英文:

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
}

huangapple
  • 本文由 发表于 2017年2月13日 04:06:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/42192628.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定