Appending to a File in Go
To write to a file in Go, you can use the ioutil.WriteFile function. However, if you want to append to a file, this function cannot be used. Instead, you can leverage the os.OpenFile function with the os.O_APPEND flag.
Here's how to append to a file in Go:
import ( "fmt" "os" ) func main() { filename := "myfile.txt" text := "New text to be appended\n" f, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600) if err != nil { fmt.Println(err) return } defer f.Close() if _, err = f.WriteString(text); err != nil { fmt.Println(err) return } }
In this code:
The above is the detailed content of How to Append Text to a File in Go?. For more information, please follow other related articles on the PHP Chinese website!