在Go代码中,我如何读取追加到二进制文件的内容?

huangapple go评论76阅读模式
英文:

In Go code, how can I read the content appended to a bin file

问题

我将为您翻译以下内容:

我将Go代码构建为二进制文件(bin/app),然后使用以下命令将一个字符串追加到二进制文件中:

echo -n -e \\x66\\x6f\\x6f  >> bin/app 

如果您使用文本编辑器打开二进制文件,您会发现在0000之后添加了内容666f 6f,这是正确的:

7465 0000 0000 0000 0000 0000 0000 0000
666f 6f

问题是如何在Go代码中读取追加到二进制文件中的内容666f 6f?非常感谢!

英文:

I build Go code to binary file (bin/app), then append a string to the binary file by using below command:

echo -n -e \\x66\\x6f\\x6f  >> bin/app 

If you open the binary file with a txt editor, you will find the added content 666f 6f after 0000, which is right:

7465 0000 0000 0000 0000 0000 0000 0000
666f 6f

The question is how can I read the content 666f 6f appendeded to the binary in Go code? Thanks a lot!

答案1

得分: 1

传统上,有第三方包(例如go-bindata)可用于将数据附加到Go二进制文件中,但是从Go 1.16开始,还有更方便的内置embed包来完成这个任务。

要实现你所要求的,你只需要“匿名”导入embed,然后使用go:embed指令将文件text.txt的内容作为变量txt可用:

package main

import _ "embed"
import "fmt"

//go:embed text.txt
var txt string

func main() {
    fmt.Println(txt);
}

对于像你的示例中的二进制数据,使用字节切片更方便:

//go:embed data.bin
var b []byte

有关更多详细信息,请参阅这篇博文官方文档

英文:

Traditionally there have been third party packages (e.g. go-bindata) available to append data to Go binaries, but as of Go 1.16, there is the even more convenient built-in embed package to do that.

All you have to do to accomplish what you asked is to "anonymously" import embed and then use the go:embed directive to make the content of the file text.txt available as the variable txt:

package main

import _ "embed"
import "fmt"

//go:embed text.txt
var txt string

func main() {
    fmt.Println(txt);
}

For binary data as in your example, it's more convenient to use a slice of bytes:

//go:embed data.bin
var b []byte

For more details, see this blog post and the official docs.

huangapple
  • 本文由 发表于 2021年12月14日 11:46:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/70343543.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定