go-013文件先读再覆盖写

阅读量: zyh 2021-12-07 18:24:12
Categories: > Tags:

涉及模块

代码

package main

import (
    "fmt"
    "os"
    "io/ioutil"
)

func main(){
    filePath := "/home/zyh/test"
    if fd, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE, 0644); err != nil {
        fmt.Printf("打开文件失败:%s\n",filePath)
    } else {
        fdbyte, _ := ioutil.ReadAll(fd)
        fmt.Printf("原始内容:%s\n", fdbyte)
        fd.Truncate(0)
        fd.Seek(0,0)
        fd.WriteString("456!")
        fd.Close()
    }
}