How to read and write binary files in Golang?
In Golang, you can utilize the os and io packages to read and write binary files.
Firstly, you can use the os.Open() function to open a binary file for reading, as shown below:
file, err := os.Open("binaryfile.bin")
if err != nil {
log.Fatal(err)
}
defer file.Close()
Next, you can use the io.ReadFull() function to read the contents of a file into a byte slice, as shown below:
data := make([]byte, filesize)
_, err = io.ReadFull(file, data)
if err != nil {
log.Fatal(err)
}
In the code above, filesize represents the size of the file, which can be obtained through the file.Stat() function. The io.ReadFull() function will read the file’s contents into the data byte slice.
To write to a binary file, you can use the os.Create() function to create a binary file for writing, as shown below:
file, err := os.Create("binaryfile.bin")
if err != nil {
log.Fatal(err)
}
defer file.Close()
Next, you can use the file.Write() function to write the content to the file, as shown below:
data := []byte{0x01, 0x02, 0x03} // 要写入的内容
_, err = file.Write(data)
if err != nil {
log.Fatal(err)
}
In the code above, `data` is the content to be written to the file, which can be a byte slice.
The above is the basic method of reading and writing binary files in Golang. It is necessary to handle them appropriately based on specific requirements and file formats.