创建一个空文本文件 [英] Create an empty text file

查看:128
本文介绍了创建一个空文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我有一个读取文件的函数,但是如果文件不存在,它会发生混乱。我想要做的是在读取之前检查文件是否存在,如果不存在,它会创建一个空文件。这是我的。

  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
}


解决方案

不要试图首先检查存在,因为如果同时创建了文件,那么您将进行竞赛。如果文件不存在,您可以使用 O_CREATE 标志打开该文件:

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


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
}

解决方案

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)

这篇关于创建一个空文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆