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.
A complete example. 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.
Result The program, once executed, will write several times to a file (you can change the path in the program).
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...
Notes, file print methods. Other methods, like WriteString() on bufio can also be used to write to a file. And these may be simpler in many programs.
However For more advanced things, like using format strings, a 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jan 11, 2024 (edit).