Create an empty text file

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()
}

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)

Tags:

Io

Go