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

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

问题描述

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

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
}

推荐答案

不要尝试先检查是否存在,因为如果同时创建文件,则会出现竞争.如果文件不存在,您可以使用 O_CREATE 标志打开文件以创建它:

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天全站免登陆