Fprint
The entire point of a file is to write things to it—to store data in it, in a persistent way. With Fprint
and its family members, we can use fmt.Print()
but target a file.
The names of these methods is confusing. F stands for file. And we use a method like Fprintf
just like fmt.Printf
—we provide a format string
. A first argument (the file) must be provided.
This program uses Fprint
, Fprintf
and Fprintln together. With Fprint
, no newline is added at the end—this helps when not writing a file of lines.
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
// Create a file and use bufio.NewWriter.
f, _ := os.Create("C:\\programs\\file.txt")
w := bufio.NewWriter(f)
// Use Fprint to write things to the file.
// ... No trailing newline is inserted.
fmt.Fprint(w, "Hello")
fmt.Fprint(w, 123)
fmt.Fprint(w, "...")
// Use Fprintf to write formatted data to the file.
value1 := "cat"
value2 := 900
fmt.Fprintf(w, "%v %d...", value1, value2)
fmt.Fprintln(w, "DONE...")
// Done.
w.Flush()
}Hello123...cat 900...DONE...
Other methods, like WriteString()
on bufio can also be used to write to a file. And these may be simpler in many programs.
func
like Fprintf
can lead to clearer code.Writing to files is a core reason for Go's existence. Go is meant to be useful in real-world tasks. Fprint
and similar methods offer a powerful tool for file writing.