Working with files
The os package (https://golang.org/pkg/os/) exposes the os.File type which represents a file handle on the system. The os.File type implements several IO primitives, including the io.Reader and io.Writer interfaces, which allows file content to be processed using the standard streaming IO API.
Creating and opening files
The os.Create function creates a new file with the specified path. If the file already exists, os.Create will overwrite it. The os.Open function, on the other hand, opens an existing file for reading.
The following source snippet opens an existing file and creates a copy of its content using the io.Copy function. One common, and recommended practice to notice is the deferred call to the method Close on the file. This ensures a graceful release of OS resources when the function exits:
func main() {
f1, err := os.Open("./file0.go")
if err != nil {
fmt.Println("Unable to open file:", err)
os.Exit(1)
} &...