Checking the Given File Exists or Not in Golang
Last Updated :
23 Mar, 2020
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:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...