Golang打開已存在的文件並覆蓋其內容


使用os.OpenFile()打開文件,flag選擇 O_WRONLY|O_TRUNC 即可

具體代碼

import (
	"fmt"
	"os"
	"bufio"
)


func main(){
	// 打開一個存在的文件,將原來的內容覆蓋掉
	path := "./hello.txt"
	// O_WRONLY: 只寫, O_TRUNC: 清空文件
	file, err := os.OpenFile(path, os.O_WRONLY | os.O_TRUNC, 0666)
	if err!=nil{
		fmt.Println("文件打開錯誤", err)
		return
	}

	defer file.Close()// 關閉文件
	// 帶緩沖區的*Writer
	writer := bufio.NewWriter(file)
	str := "hello golang\r\n"
	for i:=0;i<5;i++{
		writer.WriteString(str)
	}

	// 將緩沖區中的內容寫入到文件里
	writer.Flush()
}

結果

  • 覆寫前:
  • 覆寫后:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM