Go WriteString函数是否会引发恐慌?

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

Go WriteString function panicking?

问题

func FileFill(filename string) error {
f, err := os.Open("file.txt")
if err != nil {
panic("文件未打开")
}
defer f.Close()

for i := 0; i < 10; i++ {
    //我知道这里应该有一些错误检查
    _, err := f.WriteString("一些文本 \n")
    if err != nil {
        panic("写入文件时出错")
    }
}
return nil

}

嗨,我刚开始学习Go,并尝试一些小的用例来更好地学习它。我创建了这个函数来将文件的10行填充为"一些文本"。当我尝试加入错误检查时,程序在WriteString那一行发生了panic。我是否对某些基本概念有误解?我查看了文档,但无法弄清楚为什么会出现问题。谢谢。

英文:
func FileFill(filename string) error {
	f, err := os.Open(&quot;file.txt&quot;)
	if err != nil {
		panic(&quot;File not opened&quot;)
	}
	defer f.Close()

	for i := 0; i &lt; 10; i++ {
        //I know this should have some error checking here
		f.WriteString(&quot;some text \n&quot;)
	}
	return nil
}

Hi, I'm new to learning Go and I've been trying out some small use cases to learn it a bit better. I made this function to fill 10 lines of a file with "some text". When I tried this with error checking, the program panicked at the WriteString line. Am I misunderstanding something fundamental here? I looked at the documentation and I can't figure out why it doesn't like this. Thanks.

答案1

得分: 3

需要使用具有写入或追加权限的函数:

package main
import "os"

func main() {
   f, err := os.Create("file.txt")
   if err != nil {
      panic(err)
   }
   defer f.Close()
   for range [10]struct{}{} {
      f.WriteString("some text\n")
   }
}

https://golang.org/pkg/os#Create

英文:

Need to use a function with write or append permission:

package main
import &quot;os&quot;

func main() {
   f, err := os.Create(&quot;file.txt&quot;)
   if err != nil {
      panic(err)
   }
   defer f.Close()
   for range [10]struct{}{} {
      f.WriteString(&quot;some text\n&quot;)
   }
}

https://golang.org/pkg/os#Create

答案2

得分: 0

// 使用os.OpenFile标志选择所需的许可证
file, err := os.OpenFile(path, os.O_RDWR, 0644)

// 如果文件不存在,则创建新文件
file, err = os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0755)

// 使用O_APPEND标志将新数据追加到文件中
file, err = os.OpenFile(path, os.O_APPEND, 0755)

文档:https://pkg.go.dev/os#OpenFile

英文:
// Choose the permit you want with os.OpenFile flags
file, err := os.OpenFile(path, os.O_RDWR, 0644) 

// or crate new file if not exist
file, err = os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0755)

// or append new data into your file with O_APPEND flag
file, err = os.OpenFile(path, os.O_APPEND, 0755)

docs: https://pkg.go.dev/os#OpenFile

huangapple
  • 本文由 发表于 2021年7月5日 03:05:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/68247982.html
匿名

发表评论

匿名网友

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

确定