Checking the Given File Exists or Not in Golang
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:
// Golang program to illustrate how to check the // given file exists or not in the default directory package main import ( "log" "os" ) var ( myfile *os.FileInfo e error ) func main() { // Here Stat() function returns file info and //if there is no file, then it will return an error myfile, e := os.Stat( "gfg.txt" ) if e != nil { // Checking if the given file exists or not // Using IsNotExist() function 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:
// Golang program to illustrate how to check // the given file exists or not in given // directory package main import ( "log" "os" ) var ( myfile *os.FileInfo e error ) func main() { // Here Stat() function // returns file info and // if there is no file, // then it will return an error myfile, e := os.Stat( "/Users/anki/Documents/new_folder/myfolder/hello.txt" ) if e != nil { // Checking if the given file exists or not // Using IsNotExist() function 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:
Contact Us