...

/

Writing to a File

Writing to a File

This lesson provides code examples and their explanations for writing to a file.

We'll cover the following...

Writing data to a file

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

Press + to interact
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. The file is created if it does not exist.

The ...