英文:
How to write to a file in Go
问题
我看过https://stackoverflow.com/q/1821811/984260和http://golang.org/pkg/os/#File.Write,但是没有得到答案。
有没有办法可以直接将浮点数/整数数组写入文件,还是必须将其转换为字节/字符串才能写入。谢谢。
英文:
I have seen https://stackoverflow.com/q/1821811/984260 and http://golang.org/pkg/os/#File.Write but could not get answer.
Is there a way, I can directly write an array of float/int to a file. Or do I have to change it to byte/string to write it. Thanks.
答案1
得分: 5
你可以使用encoding/binary包中的函数来实现这个目的。
至于一次写入整个数组,没有相应的函数可以实现。你需要遍历数组并逐个写入每个元素。最好的做法是在这些元素前加上一个整数,表示数组的长度。
如果你想要一个更高级的解决方案,可以尝试使用encoding/gob包:
Package gob 管理gob流 - 在编码器(发送方)和解码器(接收方)之间交换的二进制值。一个典型的用途是传输远程过程调用(RPC)的参数和结果,例如由“rpc”包提供的那些。
英文:
You can use the functions in the encoding/binary package for this purpose.
As far as writing an entire array at once goes, there are no functions for this. You will have to iterate the array and write each element individually. Ideally, you should prefix these elements with a single integer, denoting the length of the array.
If you want a higher level solution, you can try the encoding/gob package:
> Package gob manages streams of gobs - binary values exchanged between an Encoder (transmitter) and a Decoder (receiver). A typical use is transporting arguments and results of remote procedure calls (RPCs) such as those provided by package "rpc".
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论