亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

去寫字符串函數恐慌?

去寫字符串函數恐慌?

Go
婷婷同學_ 2022-09-12 16:40:34
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


查看完整回答
反對 回復 2022-09-12
?
智慧大石

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


查看完整回答
反對 回復 2022-09-12
  • 2 回答
  • 0 關注
  • 109 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號