如何在Go中写入文件

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

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".

huangapple
  • 本文由 发表于 2013年2月1日 02:33:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/14632718.html
匿名

发表评论

匿名网友

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

确定