英文:
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("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
}
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 "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")
}
}
答案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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论