首先,使用os.Create()函数建立一个文件。 接着,使用io.WriteString()函数将内容写入文件。 最后,使用os.ReadFile()函数读取文件内容。 注意,这里读取的文件内容是data byte,我们需要使用string()函数将其转换为字符串。

package main

import (

"fmt"

"io"

"os"

)

func main() {

content := "This needs to go in a file."

file, err := os.Create("./mygofile.txt")

checkNilErr(err)

length, err := io.WriteString(file, content)

checkNilErr(err)

fmt.Println("length is: ", length)

defer file.Close()

readFile("./mygofile.txt")

}

func readFile(filename string) {

databyte, err := os.ReadFile(filename)

checkNilErr(err)

fmt.Println("Text data inside the file is \n", string(databyte))

}

func checkNilErr(err error) {

if err != nil {

panic(err)

}

}

输出为: length is: 27 Text data inside the file is This needs to go in a file.

推荐文章

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: