How to read and write binary files using Golang?

WBOY
Release: 2024-06-03 13:14:58
Original
1080 people have browsed it

如何使用 Golang 读写二进制文件?

How to use Golang to read and write binary files?

Read binary file

package main

import (
  "fmt"
  "os"
)

func main() {
  // 打开一个二进制文件
  file, err := os.Open("myfile.bin")
  if err != nil {
    fmt.Println("Error opening file:", err)
    return
  }
  defer file.Close()   // 确保文件在函数返回后关闭

  // 读取文件内容到一个字节切片
  data := make([]byte, 1024)  // 缓冲区大小可以根据需要调整
  n, err := file.Read(data)
  if err != nil {
    fmt.Println("Error reading file:", err)
    return
  }

  // 处理读取到的字节
  for i := 0; i < n; i++ {
    fmt.Printf("%02x ", data[i])  // 以十六进制打印字节
  }
  fmt.Println()
}
Copy after login

Write binary file

package main

import (
  "fmt"
  "os"
)

func main() {
  // 打开一个二进制文件,进行写操作
  file, err := os.OpenFile("myfile.bin", os.O_WRONLY|os.O_CREATE, 0644)
  if err != nil {
    fmt.Println("Error opening file:", err)
    return
  }
  defer file.Close()  // 确保文件在函数返回后关闭

  // 写入数据到文件
  data := []byte{0x01, 0x02, 0x03, 0x04}
  n, err := file.Write(data)
  if err != nil {
    fmt.Println("Error writing file:", err)
    return
  }

  // 打印写入的字节数
  fmt.Printf("Wrote %d bytes to file\n", n)
}
Copy after login

The above is the detailed content of How to read and write binary files using Golang?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template