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?
Share
For manipulating files, the
ospackage is your friend:For more control over how the file is open, see
os.OpenFile()instead (doc).For reading files, there are many ways. The
os.Filetype returned byos.Open(thefin the above example) implements theio.Readerinterface (it has aRead()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 (typebufio.Reader).Specifically for binary data, the
encoding/binarypackage 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. Thebinary.Read()function can be used with the file read using theos.Open()function, since as I mentioned, it is aio.Reader.And there’s also the simple to use
io/ioutilpackage, 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), orioutil.ReadAll()which takes aio.Readerand returns a slice of bytes containing the whole file. Here’s the doc on ioutil.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