Golang打开已存在的文件并覆盖其内容

时间:2021-02-17 14:38:25   收藏:0   阅读:0

使用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()
}

结果

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!