Generally speaking, you can use the functionality of the io.Writer
interface for writing data to files on a disk. Nevertheless, the Go code of save.go
will show you five ways to write data to a file. The save.go
program will be presented in six parts.
The first part of save.go
is as follows:
package main import ( "bufio" "fmt" "io" "io/ioutil" "os" )
The second code portion of save.go
is shown in the following Go code:
func main() { s := []byte("Data to write\n") f1, err := os.Create("f1.txt") if err != nil { fmt.Println("Cannot create file", err) return } defer f1.Close() fmt.Fprintf(f1, string(s))
Notice that the s
byte slice will be used in every line that involves writing presented in this Go program. Additionally, the fmt.Fprintf()
function used here can help you write data to your own log files using the format you want. In this case, fmt.Fprintf()
writes your data to the file identified by f1
...