HomeSearch

Golang Fprint, Fprintf and Fprintln Examples (fmt)

Use the Fprint, Fprintf and Fprintln methods from fmt to write data to a file.

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.fmt

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.File

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).

Golang program that uses Fprint, Fprintf, Fprintln 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() } Output 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.

A summary. 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.
Home
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.