Search⌘ K
AI Features

Writing to a File

Explore how to write data to files in Go, including opening files with specific flags, managing buffers with bufio.Writer, and using fmt.Fprintf for efficient writes. Understand file permissions and error handling to control file operations effectively.

We'll cover the following...

Writing data to a file

Writing data to a file is demonstrated in the following program:

Go (1.6.2)
package main
import (
"os"
"bufio"
"fmt"
)
func main () {
outputFile, outputError := os.OpenFile("output/output.dat", os.O_WRONLY|os.O_CREATE, 0666)
if outputError != nil {
fmt.Printf("An error occurred with file creation\n")
return
}
defer outputFile.Close()
outputWriter:= bufio.NewWriter(outputFile)
outputString := "hello world!\n"
for i:=0; i<10; i++ {
outputWriter.WriteString(outputString)
}
outputWriter.Flush()
}

Apart from a filehandle, we now need a writer from bufio. We open a file output.dat for write-only at line 9 ...