How to check if file exists in Golang

  • 29 March 2018
  • ADM

 

How to check if file exists in Golang - images/logos/golang.jpg

 

Here is an example how to check if a file exists using Golang.

Code

package main

import (
	"fmt"
	"os"
)

var (
	fileInfo *os.FileInfo
	err      error
)

func main() {
	fmt.Println("Check if file exists example.")
	fmt.Println()

	path := "D:\\admfactory.com\\file.txt"
	// Stat returns a FileInfo describing the named file.
	// If there is an error, it will be of type *PathError.
	fileInfo, err := os.Stat(path)
	if err != nil {
		if os.IsNotExist(err) {
			fmt.Println("'" + path + "' file does not exist.")
			// exit the application
			os.Exit(-1)
		}
	}
	fmt.Println("'" + path + "' file does exist.")
	fmt.Println()
	fmt.Println("File information:")
	fmt.Println(fileInfo)
}

Output

Check if file exists example.

'D:\admfactory.com\file.txt' file does exist.

File information:
&{file.txt {32 {940584393 30656325} {940584393 30656325} {940584393 30656325} 0
0} 0 {0 0} D:\admfactory.com\file.txt 0 0 0 false}

 

References