且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将整个文件读入字符串变量

更新时间:2022-06-24 22:38:54

使用 ioutil.ReadFile :

func ReadFile(filename string) ([]byte, error)

ReadFile读取以文件名命名的文件并返回内容.通话成功 返回err == nil,而不是err == EOF.因为ReadFile读取整个文件,所以它不会处理 读取中的EOF作为要报告的错误.

ReadFile reads the file named by filename and returns the contents. A successful call returns err == nil, not err == EOF. Because ReadFile reads the whole file, it does not treat an EOF from Read as an error to be reported.

您将得到一个[]byte而不是string.如果确实需要 ,可以将其转换:

You will get a []byte instead of a string. It can be converted if really necessary:

s := string(buf)