Go语言 操作二进制文件

king1076 · · 8935 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

二进制文件的内容:

Offset      0  1  2  3  4  5  6  7   8  9  A  B  C  D  E  F

00000000   12 31 23 12 31 22 31 23  12 31 22 22 22 22 22 22    1# 1"1# 1""""""
00000010   22 22 22 12 23 12 23 00  00 00 00 00 00 00 00 00   """ # #         
00000020   00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00                   
00000030   00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00                   
00000040   00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00                   
00000050   00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00                   
00000060   00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00                   
00000070   00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00                   
00000080   00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00                   
00000090   00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00                   
000000A0   00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00                   
000000B0   00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00                   
000000C0   00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00                   
000000D0   00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00                   

代码:

package main

import (
	"bytes"
	"fmt"
	"io"
	"os"
)

func main() {
	file, err := os.OpenFile("test", os.O_RDONLY, os.ModePerm)
	if err != nil {
		defer file.Close()
		os.Exit(0)
	}
	file.Seek(8, 0)
	fmt.Println("Success Open File")
	var buffer bytes.Buffer
	io.CopyN(&buffer, file, 8)
	_bytes := buffer.Bytes()
	var magic []byte = []byte{0x12, 0x31, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22}
	for _, byte := range _bytes {
		fmt.Printf("%02X ", byte)
	}
	fmt.Println()
	if bytes.Compare(magic, _bytes) == 0 {
		fmt.Println("Equal")
	}
}

结果:

	Success Open File
	12 31 22 22 22 22 22 22 
	Equal



有疑问加站长微信联系(非本文作者)

本文来自:CSDN博客

感谢作者:king1076

查看原文:Go语言 操作二进制文件

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

8935 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传