Create and write to files
The Go language provides support in various ways to create and write to new files. We will examine some of the most common ways in which this is performed.
The os
package provides a simple way in which to create a file. For those who are familiar with the touch
command from the Unix world, it is similar to this. Here is the signature of the function:
func Create(name string(*File, error)
The function will create an empty file much as the touch
command does. It is important to note that if the file already exists, then it will truncate the file.
The os
package’s Create
function has an input parameter, which is the name of the file to create and its location. If successful, it will return a File
type. It is worth noting that the File
type satisfies the io.Write
and io.Read
interfaces. This is important to know for later in the chapter:
package main import ( "os" ) func main() { f...