Open In App
Related Articles

Checking the Given File Exists or Not in Golang

Improve Article
Improve
Save Article
Save
Like Article
Like

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:

Checking the Given File Exists or Not in Golang

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:

Checking the Given File Exists or Not in Golang


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
Previous
Next
Similar Reads