Emi
Emi

Reputation: 545

Create an empty text file

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
}

Upvotes: 20

Views: 32536

Answers (3)

Zombo
Zombo

Reputation: 1

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

Upvotes: 0

rustyx
rustyx

Reputation: 85481

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

Upvotes: 7

Mr_Pink
Mr_Pink

Reputation: 109432

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)

Upvotes: 62

Related Questions