Working with file system in Go

Check if file exists

In order to check whether the given file exists or not, we can use the os.Stat function. As you can see from the example below, we are ignoring the actual output of the os.Stat function, we are only checking whether its call produces an error or not. If there is no error, we can state that the given file exists.

import (
	"fmt"
	"os"
)

func main() {
	if _, err := os.Stat("./testfile"); err != nil {
		fmt.Println("Error getting file data")
	} else {
		fmt.Println("File exists")
	}
}

Copy file

A simple way to copy a small file is to read the source file content to an array of bytes and then to write it to the destination file.

b, err := os.ReadFile("./sourcefile")
if err != nil {
    log.Fatalf("error reading the source file: %v", err)
}
if err = os.WriteFile("./destinationfile", b, 0644); err != nil {
    log.Fatalf("error writing to the destination file: %v", err)
}