As we have seen for reading, there are different ways to write files, each one with its own flaws and strengths. In the ioutil package, for instance, we have another function called WriteFile that allows us to execute the whole operation in one line. This includes opening the file, writing its contents, and then closing it.
An example of writing all a file's content at once is shown in the following code:
package main
import (
"fmt"
"io/ioutil"
"os"
)
func main() {
if len(os.Args) != 3 {
fmt.Println("Please specify a path and some content")
return
}
// the second argument, the content, needs to be casted to a byte slice
if err := ioutil.WriteFile(os.Args[1], []byte(os.Args[2]), 0644); err != nil {
fmt.Println("Error:", err)
}
}
This example writes all the content at...