To check if a file with a given file path exists or not in the go programming language we make use of IsNotExist and stat functions from the os package
type FileInfo interface {
Name() string // base name of the file
Size() int64 // length in bytes for regular files; system-dependent for others
Mode() FileMode // file mode bits
ModTime() time.Time // modification time
IsDir() bool // abbreviation for Mode().IsDir()
Sys() interface{} // underlying data source (can return nil)
}
Go ( Golang ) : Checking if a file with a given filepath exists
package main
import (
"fmt"
"os"
)
/* The below function checks if a regular file (not directory) with a
given filepath exist */
func FileExists (filepath string) bool {
fileinfo, err := os.Stat(filepath)
if os.IsNotExist(err) {
return false
}
// Return false if the fileinfo says the file path is a directory.
return !fileinfo.IsDir()
}
func main() {
// File xyz has been created in /tmp folder
var filepath = "/tmp/xyz"
if FileExists(filepath) {
fmt.Println("File " + filepath + " exist")
} else {
fmt.Println("File " + filepath + " does not exist")
}
// /tmp being a directory (not a file) is reported as not existing
filepath = "/tmp"
if FileExists(filepath) {
fmt.Println("File " + filepath + " exist")
} else {
fmt.Println("File " + filepath + " does not exist")
}
}
Output
File /tmp/xyz exist
File /tmp does not exist