去写字符串函数恐慌?

func FileFill(filename string) error {

    f, err := os.Open("file.txt")

    if err != nil {

        panic("File not opened")

    }

    defer f.Close()


    for i := 0; i < 10; i++ {

        //I know this should have some error checking here

        f.WriteString("some text \n")

    }

    return nil

}

嗨,我是学习Go的新手,我一直在尝试一些小用例来更好地学习它。我创建这个函数是用“一些文本”填充文件的10行。当我尝试使用错误检查进行此操作时,程序在写字符串行处崩溃。我在这里误解了一些基本的东西吗?我看了文档,我不明白为什么它不喜欢这个。谢谢。


婷婷同学_
浏览 117回答 2
2回答

倚天杖

需要使用具有写入或追加权限的函数:package mainimport "os"func main() {&nbsp; &nbsp;f, err := os.Create("file.txt")&nbsp; &nbsp;if err != nil {&nbsp; &nbsp; &nbsp; panic(err)&nbsp; &nbsp;}&nbsp; &nbsp;defer f.Close()&nbsp; &nbsp;for range [10]struct{}{} {&nbsp; &nbsp; &nbsp; f.WriteString("some text\n")&nbsp; &nbsp;}}https://golang.org/pkg/os#Create

智慧大石

// Choose the permit you want with os.OpenFile flagsfile, err := os.OpenFile(path, os.O_RDWR, 0644)&nbsp;// or crate new file if not existfile, err = os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0755)// or append new data into your file with O_APPEND flagfile, err = os.OpenFile(path, os.O_APPEND, 0755)文档: https://pkg.go.dev/os#OpenFile
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go