Menu Close

Go – How to check if a file exists in Go

Here, We will see how to check if a file exists in Go. We can do it by using Stat() function in os package in go golang.

Function prototype:

func Stat(name string) (FileInfo, error)

Input Parameter:

name : file name

Return value:

Stat() function in os package returns
a FileInfo describing the named file.

If there is an error, it will be of type 
*PathError.

Example with code:

package main

import (

  "fmt"

  "os"
)

func main() {

  file_name := "/Usr/sample.go"

  if _, err := os.Stat(file_name); err == nil {

    fmt.Println("File exists")

  } else if os.IsNotExist(err) {

    fmt.Println("File or path doesn't exists")

  } else {

    fmt.Println(err)

  }

}

Output:

File exists

To learn more about golang, Please refer given below link:

https://techieindoor.com/go-lang-tutorial/

References:

https://golang.org/doc/
https://golang.org/pkg/
Posted in golang, os, packages

Leave a Reply

Your email address will not be published. Required fields are marked *