Go WriteString function panicking?

Viewed 338
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
}

Hi, I'm new to learning Go and I've been trying out some small use cases to learn it a bit better. I made this function to fill 10 lines of a file with "some text". When I tried this with error checking, the program panicked at the WriteString line. Am I misunderstanding something fundamental here? I looked at the documentation and I can't figure out why it doesn't like this. Thanks.

2 Answers

Need to use a function with write or append permission:

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

// 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)

docs: https://pkg.go.dev/os#OpenFile

Related