-3

I try to use the following code

appendStr := []byte("append test")
ioutil.WriteFile("./test.txt", appendStr, os.ModeAppend)

but it seems does not work

LuisH
  • 35
  • 5
  • 1
    What happens when you run the above code? Does it overwrite the file, or result in an error, or something else? – larsks May 02 '22 at 15:30
  • 2
    You have to open a file in append mode to automatically append to it. This is not something `ioutil` alone (a package which is no longer needed, all functionality is handled by `io` or `os`) can do – JimB May 02 '22 at 15:34
  • 3
    The documentation seems clear: *If the file does not exist, WriteFile creates it ... otherwise WriteFile truncates it before writing...* The `perm` argument is only used to set permissions on a newly created file. – aMike May 02 '22 at 16:56

1 Answers1

2

As JimB already explained

appendStr := []byte("\n append test")
f, err := os.OpenFile("text.log", os.O_APPEND, 0666)
if err != nil {
    fmt.Println(err)
    return
}
defer f.Close()
n, err := f.Write(appendStr)
if err != nil {
    fmt.Println(err)
    return
}
fmt.Printf("wrote %d bytes\n", n)
Manjeet Thakur
  • 2,288
  • 1
  • 16
  • 35