Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an empty text file

Tags:

io

go

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
}
like image 949
CoppolaEmilio Avatar asked Feb 22 '16 16:02

CoppolaEmilio


People also ask

What is an empty text file?

Empty files are those with a file size of zero bytes and no data stored in them. You can make an empty text file, word document, or whatever you want. With the "touch" command in Linux, we can easily create an empty file. In Windows OS, there is no direct equivalent command for touch.

Which command create an empty file?

Explanation: The touch command creates a new empty file. You can create multiple files with the same command.


1 Answers

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)
like image 73
JimB Avatar answered Sep 20 '22 13:09

JimB