简体   繁体   English

如何在Go中写入文件

[英]How to write to a file in Go

I have seen How to read/write from/to file using golang? 我已经看过如何使用golang从文件读/写文件吗? and http://golang.org/pkg/os/#File.Write but could not get answer. http://golang.org/pkg/os/#File.Write,但无法获得答案。

Is there a way, I can directly write an array of float/int to a file. 有没有办法,我可以直接将float / int数组写入文件。 Or do I have to change it to byte/string to write it. 还是我必须将其更改为字节/字符串才能编写它。 Thanks. 谢谢。

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: 如果您需要更高级别的解决方案,可以尝试encoding / gob软件包:

Package gob manages streams of gobs - binary values exchanged between an Encoder (transmitter) and a Decoder (receiver). 软件包gob管理gob的流-编码器(发送器)和解码器(接收器)之间交换的二进制值。 A typical use is transporting arguments and results of remote procedure calls (RPCs) such as those provided by package "rpc". 一种典型的用法是传输远程过程调用(RPC)的参数和结果,例如程序包“ rpc”所提供的参数和结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM