In Go language, you are allowed to check whether the given file exists or not with the help of the IsNotExist() function. If this function returns true, then it indicates that the error is known to report that the specified file or directory already does not exist and if it returns false, then it indicates that the given file or directory exists. This method also satisfied by ErrNotExist as well as some syscall errors. It is defined under the os package so, you have to import os package in your program for accessing IsNotExist() function.
Syntax:
func IsNotExist(e error) bool
Example 1:
package main
import (
"log"
"os"
)
var (
myfile *os.FileInfo
e error
)
func main() {
myfile, e := os.Stat( "gfg.txt" )
if e != nil {
if os.IsNotExist(e) {
log .Fatal( "File not Found !!" )
}
}
log .Println( "File Exist!!" )
log .Println( "Detail of file is:" )
log .Println( "Name: " , myfile.Name())
log .Println( "Size: " , myfile.Size())
}
|
Output:

Example 2:
package main
import (
"log"
"os"
)
var (
myfile *os.FileInfo
e error
)
func main() {
myfile, e := os.Stat( "/Users/anki/Documents/new_folder/myfolder/hello.txt" )
if e != nil {
if os.IsNotExist(e) {
log .Fatal( "File not Found !!" )
}
}
log .Println( "File Exist!!" )
log .Println( "Detail of file is:" )
log .Println( "Name: " , myfile.Name())
log .Println( "Size: " , myfile.Size())
}
|
Output:

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
23 Mar, 2020
Like Article
Save Article