如何在Go中读取二进制文件 [英] How to read a binary file in Go

查看:775
本文介绍了如何在Go中读取二进制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Go完全陌生,我试图读取一个二进制文件,一次一个字节地读取,也可以一次读取几个字节.该文档并没有多大帮助,我找不到任何教程或简单示例(顺便说一句,Google如何给他们的语言提供这样一个难以理解的名称?).基本上,我如何打开文件,然后将一些字节读入缓冲区?有什么建议吗?

I'm completely new to Go and I'm trying to read a binary file, either byte by byte or several bytes at a time. The documentation doesn't help much and I cannot find any tutorial or simple example (by the way, how could Google give their language such an un-googlable name?). Basically, how can I open a file, then read some bytes into a buffer? Any suggestion?

推荐答案

要处理文件,os包是您的朋友:

For manipulating files, the os package is your friend:

f, err := os.Open("myfile")
if err != nil {
   panic(err)
}
defer f.Close()

要进一步控制文件的打开方式,请参见os.OpenFile(),而不是(doc).

For more control over how the file is open, see os.OpenFile() instead (doc).

要读取文件,有很多方法.由os.Open返回的os.File类型(在上例中为f)实现了io.Reader接口(它具有带有正确签名的Read()方法),可以直接用于读取其中的某些数据.缓冲区([]byte),也可以将其包装在缓冲的读取器中(类型bufio.Reader).

For reading files, there are many ways. The os.File type returned by os.Open (the f in the above example) implements the io.Reader interface (it has a Read() method with the right signature), it can be used directly to read some data in a buffer (a []byte) or it can also be wrapped in a buffered reader (type bufio.Reader).

特别是对于二进制数据,encoding/binary包可以用于将字节序列读入某种类型的数据结构中.您可以在此处转到文档中查看示例. binary.Read()函数可以与使用os.Open()函数读取的文件一起使用,因为如上所述,它是io.Reader.

Specifically for binary data, the encoding/binary package can be useful, to read a sequence of bytes into some typed structure of data. You can see an example in the Go doc here. The binary.Read() function can be used with the file read using the os.Open() function, since as I mentioned, it is a io.Reader.

还有一个简单易用的io/ioutil包,它允许您一次读取一个字节片中的整个文件(ioutil.ReadFile(),它具有文件名,因此您甚至不必打开/请自行关闭文件),或ioutil.ReadAll()接受io.Reader并返回包含整个文件的字节片.这是ioutil上的文档.

And there's also the simple to use io/ioutil package, that allows you to read the whole file at once in a byte slice (ioutil.ReadFile(), which takes a file name, so you don't even have to open/close the file yourself), or ioutil.ReadAll() which takes a io.Reader and returns a slice of bytes containing the whole file. Here's the doc on ioutil.

最后,就像其他人提到的那样,您可以使用"golang"在Go语言中搜索Google,然后您将找到所需的所有内容. golang-nuts邮件列表也是寻找答案的好地方(确保在发布之前先搜索,已经回答了很多东西).要查找第三方程序包,请访问 godoc.org 网站.

Finally, as others mentioned, you can google about the Go language using "golang" and you should find all you need. The golang-nuts mailing list is also a great place to look for answers (make sure to search first before posting, a lot of stuff has already been answered). To look for third-party packages, check the godoc.org website.

HTH

这篇关于如何在Go中读取二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆