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行。當我嘗試使用錯誤檢查進行此操作時,程序在寫字符串行處崩潰。我在這里誤解了一些基本的東西嗎?我看了文檔,我不明白為什么它不喜歡這個。謝謝。
2 回答

倚天杖
TA貢獻1828條經驗 獲得超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

智慧大石
TA貢獻1946條經驗 獲得超3個贊
// 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)
文檔: https://pkg.go.dev/os#OpenFile
- 2 回答
- 0 關注
- 109 瀏覽
添加回答
舉報
0/150
提交
取消