golang simple read write file example

  • 2020-06-01 09:58:40
  • OfStack

This article illustrates a simple way for golang to read and write files. I will share it with you for your reference as follows:

Here's how golang can read and write files:

package main
import (
    "fmt"
    "os"
)
func main() {
    f, err := os.OpenFile("file2.txt", os.O_RDWR | os.O_CREATE | os.O_APPEND, 0x644)
    if err != nil {
        panic(err)
    }
    defer f.Close()
    wint, err := f.WriteString("helloworld")
    if err != nil {
        panic(err)
    }
    fmt.Printf("%d\n", wint)
    _, err = f.Seek(0, 0)
    if err != nil {
        panic(err)
    }
    bs := make([]byte, 100)
    rint, err := f.Read(bs)
    if err != nil {
        panic(err)
    }
    fmt.Printf("%d, %s\n", rint, bs)
}

I hope this article has been helpful to you in the programming of Go language.


Related articles: