英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论