在golang中,如果文件不存在,os.OpenFile函数不会返回os.ErrNotExist。

huangapple go评论80阅读模式
英文:

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

问题

我正在尝试打开一个文件,并且我想知道如果文件不存在时应该如何处理。但是,当文件不存在时,使用以下代码:

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

返回的错误与os.ErrNotExists不同:

os.ErrNotExists -> "文件不存在"
err.(*os.PathError).Err -> "没有这样的文件或目录"

如果文件不存在,os.Stat也会返回相同的错误。是否有预定义的错误可以进行比较,而不是手动处理呢?

英文:

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?

答案1

得分: 23

> 包 os
>
> func IsExist
>
> func IsExist(err error) bool
>
> IsExist 函数返回一个布尔值,指示错误是否已知为文件或目录已存在的报告。它适用于 ErrExist 和一些系统调用错误。
>
> func IsNotExist
>
> func IsNotExist(err error) bool
>
> IsNotExist 函数返回一个布尔值,指示错误是否已知为文件或目录不存在的报告。它适用于 ErrNotExist 和一些系统调用错误。

使用 os.IsNotExist 函数。例如:

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("文件不存在:")
		}
		fmt.Println(err)
	}
}

输出:

文件不存在:open No File: 没有该文件或目录
英文:

> 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

答案2

得分: 2

根据Go 1.17的最新规定,检查这个错误的首选方法是:

errors.Is(err, fs.ErrNotExist)

来源

英文:

Originally posted as an anonymous suggested edit to the other answer:

As of Go 1.17, the preferred way to check for this error is:

errors.Is(err, fs.ErrNotExist)

Source

huangapple
  • 本文由 发表于 2015年10月29日 01:48:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/33398110.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定