Hello,
The default behaviour of os.Create is to truncate the file if already
exists. I wrote the code below to control whether the file should be
overwritten or not (possibly based on user wishes). Seems to work on MacOS.
Do you think this code will work on Windows and Linux? Do you see any
subtle issues with races etc.
Thanks,
func CreateFile(fileName string, overWrite bool) (out *os.File, err error) {
out, err = os.OpenFile(fileName, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0666)
switch {
case os.IsExist(err): //failed because file already exists
if overWrite {
return os.OpenFile(fileName, os.O_RDWR|os.O_CREATE|os.O_TRUNC,
0666) //overwrite it
}
return nil, fmt.Errorf("file %s already exists", fileName)
default: //no errors or errors other than file exists
return out, err
}
}
--
You received this message because you are subscribed to the Google Groups
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.