Golang : Check If The File Exists

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

  • Function IsNotExist : IsNotExist ( err error ) bool is used to check if the given file path is a file or a directory.
    IsNotExist returns true if the filepath is a file or a directory.
  • Function stat : ( f *File ) Stat ( ) ( FileInfo, error ) returns FileInfo structure that describes the file. If the FileInfo structure tells us that the provided filepath is a directory, we return false.

    FileInfo
    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


Copyright (c) 2019-2024, Algotree.org.
All rights reserved.