Create an empty text file

前端 未结 2 1783
梦毁少年i
梦毁少年i 2020-12-15 21:41

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 pani

相关标签:
2条回答
  • 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)
    
    0 讨论(0)
  • 2020-12-15 22:27

    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()
    }
    
    0 讨论(0)
提交回复
热议问题