Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In golang os.OpenFile doesn't return os.ErrNotExist if file does not exist

I'm trying to open a file and I'd like to know if it doesn't exist to react. But the error

os.OpenFile(fName, os.O_WRONLY, 0600) 

returns when the file does not exist is different than os.ErrNotExists

os.ErrNotExists -> "file does not exist"
err.(*os.PathError).Err -> "no such file or directory"

os.Stat also return the same error if the file is not there. Is there a predefined error I can compare to instead of having to do it by hand?

like image 746
Adrià Casajús Avatar asked Oct 28 '15 17:10

Adrià Casajús


People also ask

How do you check whether a file exists or not in Golang?

In order to check if a particular file exists inside a given directory in Golang, we can use the Stat() and the isNotExists() function that the os package of Go's standard library provides us with. The Stat() function is used to return the file info structure describing the file.

What does the write function from the os package return in Golang?

To write to files in Go, we use the os , ioutil , and fmt packages. The functions that we use typically return the number of bytes written and an error, if any.

What does os stat do in Golang?

The os. Stat function attempts to resolve the path relative to the root of your project directory. If a matching file or directory is not found, it will attempt to resolve the path relative to the contentDir . A leading path separator ( / ) is optional.

What is os stdout?

Stdout, also known as standard output, is the default file descriptor where a process can write output. In Unix-like operating systems, such as Linux, macOS X, and BSD, stdout is defined by the POSIX standard. Its default file descriptor number is 1.


1 Answers

Package os

func IsExist

func IsExist(err error) bool

IsExist returns a boolean indicating whether the error is known to report that a file or directory already exists. It is satisfied by ErrExist as well as some syscall errors.

func IsNotExist

func IsNotExist(err error) bool

IsNotExist returns a boolean indicating whether the error is known to report that a file or directory does not exist. It is satisfied by ErrNotExist as well as some syscall errors.

Use the os.IsNotExist function. For example,

package main

import (
    "fmt"
    "os"
)

func main() {
    fname := "No File"
    _, err := os.OpenFile(fname, os.O_WRONLY, 0600)
    if err != nil {
        if os.IsNotExist(err) {
            fmt.Print("File Does Not Exist: ")
        }
        fmt.Println(err)
    }
}

Output:

File Does Not Exist: open No File: No such file or directory
like image 102
peterSO Avatar answered Oct 07 '22 12:10

peterSO