File I/O operations
Now that you know the basics of the io
and bufio
packages, it is time to learn more detailed information about their usage and how they can help you work with files. But first, we will talk about the fmt.Fprintf()
function.
Writing to files using fmt.Fprintf()
The use of the fmt.Fprintf()
function allows you to write formatted text to files in a way that is similar to the way the fmt.Printf()
function works. Note that fmt.Fprintf()
can write to any io.Writer
interface and that our files will satisfy the io.Writer
interface.
The Go code that illustrates the use of fmt.Fprintf()
can be found in fmtF.go
, which will be presented in three parts. The first part is the expected preamble:
package main import ( "fmt" "os" )
The second part has the following Go code:
func main() { if len(os.Args) != 2 { fmt.Println("Please provide a filename") os.Exit(1) } filename := os.Args[1] destination, err := os.Create(filename) if err != nil...