英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论