创建一个空的文本文件。

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

Create an empty text file

问题

我一直在阅读和搜索,但似乎找不到这个简单的答案。

我有一个函数用于读取文件,但如果文件不存在,它会引发 panic。我想做的是在读取之前检查文件是否存在,如果不存在,则创建一个空文件。以下是我的代码:

func exists(path string) (bool, error) {
    _, err := os.Stat(path)
    if err == nil {
        return true, nil
    }
    if os.IsNotExist(err) {
        return false, nil
    }
    return true, err
}

请帮我翻译这段代码。

英文:

I've been reading and googling all over but I can't seem to find this simple answer.

I have a function that reads a file, but if the files doesn't exists it panics. What I want to do is a function that before reading, checks if the files exists, and if not, it creates an empty file. Here is what I have.

func exists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return true, err
}

答案1

得分: 56

不要尝试先检查文件是否存在,因为如果文件在同一时间被创建,那么就会出现竞争问题。你可以使用O_CREATE标志打开文件,如果文件不存在,则创建它:

os.OpenFile(name, os.O_RDONLY|os.O_CREATE, 0666)
英文:

Don't try to check the existence first, since you then have a race if the file is created at the same time. You can open the file with the O_CREATE flag to create it if it doesn't exist:

os.OpenFile(name, os.O_RDONLY|os.O_CREATE, 0666)

答案2

得分: 7

只是试图改进这个优秀的被接受的答案。

检查错误并Close()打开的文件是一个好主意,因为文件描述符是有限资源。你可能会在GC运行之前耗尽文件描述符,在Windows上可能会遇到文件共享违规问题。

func TouchFile(name string) error {
    file, err := os.OpenFile(name, os.O_RDONLY|os.O_CREATE, 0644)
    if err != nil {
        return err
    }
    return file.Close()
}
英文:

Just trying to improve the excellent accepted answer.

It's a good idea to check for errors and to Close() the opened file, since file descriptors are a limited resource. You can run out of file descriptors much sooner than a GC runs, and on Windows you can run into file sharing violations.

func TouchFile(name string) error {
    file, err := os.OpenFile(name, os.O_RDONLY|os.O_CREATE, 0644)
    if err != nil {
        return err
    }
    return file.Close()
}

答案3

得分: 0

OpenFile函数是实现这个功能的最佳方法,但这里还有另一种选择:

package main
import "os"

func create(name string) (*os.File, error) {
   _, e := os.Stat(name)
   if e == nil { return nil, os.ErrExist }
   return os.Create(name)
}

func main() {
   f, e := create("file.txt")
   if os.IsExist(e) {
      println("Exist")
   } else if e != nil {
      panic(e)
   }
   f.Close()
}

https://golang.org/pkg/os#ErrExist

英文:

The OpenFile function is the best way to do this, but here is another option:

package main
import "os"

func create(name string) (*os.File, error) {
   _, e := os.Stat(name)
   if e == nil { return nil, os.ErrExist }
   return os.Create(name)
}

func main() {
   f, e := create("file.txt")
   if os.IsExist(e) {
      println("Exist")
   } else if e != nil {
      panic(e)
   }
   f.Close()
}

https://golang.org/pkg/os#ErrExist

huangapple
  • 本文由 发表于 2016年2月23日 00:28:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/35558787.html
匿名

发表评论

匿名网友

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

确定